code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType A_ = logging.get_logger(__name__) A_ = { "openai/whisper-base": "https://huggingface.co/openai/whisper-base/resolve/main/config.json", } # fmt: off A_ = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1_058, 1_220, 1_267, 1_279, 1_303, 1_343, 1_377, 1_391, 1_635, 1_782, 1_875, 2_162, 2_361, 2_488, 3_467, 4_008, 4_211, 4_600, 4_808, 5_299, 5_855, 6_329, 7_203, 9_609, 9_959, 10_563, 10_786, 11_420, 11_709, 11_907, 13_163, 13_697, 13_700, 14_808, 15_306, 16_410, 16_791, 17_992, 19_203, 19_510, 20_724, 22_305, 22_935, 27_007, 30_109, 30_420, 33_409, 34_949, 40_283, 40_493, 40_549, 47_282, 49_146, 50_257, 50_359, 50_360, 50_361 ] A_ = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1_350, 1_853, 1_982, 2_460, 2_627, 3_246, 3_253, 3_268, 3_536, 3_846, 3_961, 4_183, 4_667, 6_585, 6_647, 7_273, 9_061, 9_383, 10_428, 10_929, 11_938, 12_033, 12_331, 12_562, 13_793, 14_157, 14_635, 15_265, 15_618, 16_553, 16_604, 18_362, 18_956, 20_075, 21_675, 22_520, 26_130, 26_161, 26_435, 28_279, 29_464, 31_650, 32_302, 32_470, 36_865, 42_863, 47_425, 49_870, 50_254, 50_258, 50_360, 50_361, 50_362 ] class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'whisper' SCREAMING_SNAKE_CASE_ = ['past_key_values'] SCREAMING_SNAKE_CASE_ = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=51865 , SCREAMING_SNAKE_CASE_=80 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1536 , SCREAMING_SNAKE_CASE_=1536 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=50257 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1500 , SCREAMING_SNAKE_CASE_=448 , SCREAMING_SNAKE_CASE_=50256 , SCREAMING_SNAKE_CASE_=50256 , SCREAMING_SNAKE_CASE_=50256 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=[220, 50256] , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.05 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=7 , **SCREAMING_SNAKE_CASE_ , ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = vocab_size lowerCamelCase_ = num_mel_bins lowerCamelCase_ = d_model lowerCamelCase_ = encoder_layers lowerCamelCase_ = encoder_attention_heads lowerCamelCase_ = decoder_layers lowerCamelCase_ = decoder_attention_heads lowerCamelCase_ = decoder_ffn_dim lowerCamelCase_ = encoder_ffn_dim lowerCamelCase_ = dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = activation_function lowerCamelCase_ = init_std lowerCamelCase_ = encoder_layerdrop lowerCamelCase_ = decoder_layerdrop lowerCamelCase_ = use_cache lowerCamelCase_ = encoder_layers lowerCamelCase_ = scale_embedding # scale factor will be sqrt(d_model) if True lowerCamelCase_ = max_source_positions lowerCamelCase_ = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. lowerCamelCase_ = classifier_proj_size lowerCamelCase_ = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowerCamelCase_ = apply_spec_augment lowerCamelCase_ = mask_time_prob lowerCamelCase_ = mask_time_length lowerCamelCase_ = mask_time_min_masks lowerCamelCase_ = mask_feature_prob lowerCamelCase_ = mask_feature_length lowerCamelCase_ = mask_feature_min_masks lowerCamelCase_ = median_filter_width super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , suppress_tokens=SCREAMING_SNAKE_CASE_ , begin_suppress_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' @property def UpperCamelCase( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' lowerCamelCase_ = OrderedDict( [ ('input_features', {0: 'batch', 1: 'feature_size', 2: 'encoder_sequence'}), ] ) if self.use_past: lowerCamelCase_ = {0: 'batch'} else: lowerCamelCase_ = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE_ , direction='inputs' ) return common_inputs def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = -1 , SCREAMING_SNAKE_CASE_ = -1 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 22050 , SCREAMING_SNAKE_CASE_ = 5.0 , SCREAMING_SNAKE_CASE_ = 220 , ) -> Mapping[str, Any]: '''simple docstring''' lowerCamelCase_ = OrderedDict() lowerCamelCase_ = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=SCREAMING_SNAKE_CASE_ , framework=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , time_duration=SCREAMING_SNAKE_CASE_ , frequency=SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = encoder_inputs['input_features'].shape[2] lowerCamelCase_ = encoder_sequence_length // 2 if self.use_past else seq_length lowerCamelCase_ = super().generate_dummy_inputs( preprocessor.tokenizer , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = encoder_inputs.pop('input_features' ) lowerCamelCase_ = decoder_inputs.pop('decoder_input_ids' ) if "past_key_values" in decoder_inputs: lowerCamelCase_ = decoder_inputs.pop('past_key_values' ) return dummy_inputs @property def UpperCamelCase( self ) -> float: '''simple docstring''' return 1E-3
42
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} A_ = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } A_ = { "allenai/longformer-base-4096": 4_096, "allenai/longformer-large-4096": 4_096, "allenai/longformer-large-4096-finetuned-triviaqa": 4_096, "allenai/longformer-base-4096-extra.pos.embd.only": 4_096, "allenai/longformer-large-4096-extra.pos.embd.only": 4_096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _UpperCamelCase ( ) -> Any: lowerCamelCase_ = ( list(range(ord('!' ) ,ord('~' ) + 1 ) ) + list(range(ord('¡' ) ,ord('¬' ) + 1 ) ) + list(range(ord('®' ) ,ord('ÿ' ) + 1 ) ) ) lowerCamelCase_ = bs[:] lowerCamelCase_ = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 lowerCamelCase_ = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase ,__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: lowerCamelCase_ = set() lowerCamelCase_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCamelCase_ = char return pairs class UpperCAmelCase ( UpperCAmelCase__ ): '''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 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="replace" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else bos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else eos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else sep_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else cls_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else unk_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( errors=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as vocab_handle: lowerCamelCase_ = json.load(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {v: k for k, v in self.encoder.items()} lowerCamelCase_ = errors # how to handle errors in decoding lowerCamelCase_ = bytes_to_unicode() lowerCamelCase_ = {v: k for k, v in self.byte_encoder.items()} with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as merges_handle: lowerCamelCase_ = merges_handle.read().split('\n' )[1:-1] lowerCamelCase_ = [tuple(merge.split() ) for merge in bpe_merges] lowerCamelCase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowerCamelCase_ = {} lowerCamelCase_ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowerCamelCase_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' return len(self.encoder ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' if token in self.cache: return self.cache[token] lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) if not pairs: return token while True: lowerCamelCase_ = min(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break lowerCamelCase_ ,lowerCamelCase_ = bigram lowerCamelCase_ = [] lowerCamelCase_ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): try: lowerCamelCase_ = word.index(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCamelCase_ = j if word[i] == first and i < len(SCREAMING_SNAKE_CASE_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = new_word if len(SCREAMING_SNAKE_CASE_ ) == 1: break else: lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = ' '.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = word return word def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' lowerCamelCase_ = [] for token in re.findall(self.pat , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(SCREAMING_SNAKE_CASE_ ).split(' ' ) ) return bpe_tokens def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' return self.encoder.get(SCREAMING_SNAKE_CASE_ , self.encoder.get(self.unk_token ) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' return self.decoder.get(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = ''.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) + '\n' ) lowerCamelCase_ = 0 with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ' Please check that the tokenizer is not corrupted!' ) lowerCamelCase_ = token_index writer.write(' '.join(SCREAMING_SNAKE_CASE_ ) + '\n' ) index += 1 return vocab_file, merge_file def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] lowerCamelCase_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' lowerCamelCase_ = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(SCREAMING_SNAKE_CASE_ ) > 0 and not text[0].isspace()): lowerCamelCase_ = ' ' + text return (text, kwargs)
42
1
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation A_ = logging.get_logger(__name__) A_ = {"tokenizer_file": "tokenizer.json"} A_ = { "tokenizer_file": { "bigscience/tokenizer": "https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json", "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json", "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json", "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json", "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json", "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json", "bigscience/bloom": "https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json", }, } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = ['input_ids', 'attention_mask'] SCREAMING_SNAKE_CASE_ = None def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ) -> Dict: '''simple docstring''' super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , SCREAMING_SNAKE_CASE_ ) != add_prefix_space: lowerCamelCase_ = getattr(SCREAMING_SNAKE_CASE_ , pre_tok_state.pop('type' ) ) lowerCamelCase_ = add_prefix_space lowerCamelCase_ = pre_tok_class(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = add_prefix_space def UpperCamelCase( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> BatchEncoding: '''simple docstring''' lowerCamelCase_ = kwargs.get('is_split_into_words' , SCREAMING_SNAKE_CASE_ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' ' pretokenized inputs.' ) return super()._batch_encode_plus(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> BatchEncoding: '''simple docstring''' lowerCamelCase_ = kwargs.get('is_split_into_words' , SCREAMING_SNAKE_CASE_ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' ' pretokenized inputs.' ) return super()._encode_plus(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' lowerCamelCase_ = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) + [self.eos_token_id] ) if len(SCREAMING_SNAKE_CASE_ ) > self.model_max_length: lowerCamelCase_ = input_ids[-self.model_max_length :] return input_ids
42
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} A_ = { "vocab_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt" ), "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt", "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt", "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt", "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt", }, "tokenizer_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json" ), "google/realm-orqa-nq-openqa": ( "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-nq-reader": ( "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-openqa": ( "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-reader": ( "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json" ), }, } A_ = { "google/realm-cc-news-pretrained-embedder": 512, "google/realm-cc-news-pretrained-encoder": 512, "google/realm-cc-news-pretrained-scorer": 512, "google/realm-cc-news-pretrained-openqa": 512, "google/realm-orqa-nq-openqa": 512, "google/realm-orqa-nq-reader": 512, "google/realm-orqa-wq-openqa": 512, "google/realm-orqa-wq-reader": 512, } A_ = { "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-reader": {"do_lower_case": True}, "google/realm-orqa-wq-openqa": {"do_lower_case": True}, "google/realm-orqa-wq-reader": {"do_lower_case": True}, } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ = RealmTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="[UNK]" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="[PAD]" , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[MASK]" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> List[Any]: '''simple docstring''' super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , do_lower_case=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , SCREAMING_SNAKE_CASE_ ) != do_lower_case or normalizer_state.get('strip_accents' , SCREAMING_SNAKE_CASE_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , SCREAMING_SNAKE_CASE_ ) != tokenize_chinese_chars ): lowerCamelCase_ = getattr(SCREAMING_SNAKE_CASE_ , normalizer_state.pop('type' ) ) lowerCamelCase_ = do_lower_case lowerCamelCase_ = strip_accents lowerCamelCase_ = tokenize_chinese_chars lowerCamelCase_ = normalizer_class(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = do_lower_case def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = PaddingStrategy.MAX_LENGTH lowerCamelCase_ = text lowerCamelCase_ = kwargs.pop('text_pair' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = kwargs.pop('return_tensors' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'input_ids': [], 'attention_mask': [], 'token_type_ids': [], } for idx, candidate_text in enumerate(SCREAMING_SNAKE_CASE_ ): if batch_text_pair is not None: lowerCamelCase_ = batch_text_pair[idx] else: lowerCamelCase_ = None lowerCamelCase_ = super().__call__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = encoded_candidates.get('input_ids' ) lowerCamelCase_ = encoded_candidates.get('attention_mask' ) lowerCamelCase_ = encoded_candidates.get('token_type_ids' ) if encoded_input_ids is not None: output_data["input_ids"].append(SCREAMING_SNAKE_CASE_ ) if encoded_attention_mask is not None: output_data["attention_mask"].append(SCREAMING_SNAKE_CASE_ ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {key: item for key, item in output_data.items() if len(SCREAMING_SNAKE_CASE_ ) != 0} return BatchEncoding(SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' lowerCamelCase_ = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
42
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def UpperCamelCase( self ) -> int: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , ) return model @property def UpperCamelCase( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) lowerCamelCase_ = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) lowerCamelCase_ = DDPMScheduler() lowerCamelCase_ = AudioDiffusionPipeline(vqvae=SCREAMING_SNAKE_CASE_ , unet=self.dummy_unet , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , steps=4 ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = output.images[0] lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , steps=4 , return_dict=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 lowerCamelCase_ = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) lowerCamelCase_ = DDIMScheduler() lowerCamelCase_ = self.dummy_vqvae_and_unet lowerCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) np.random.seed(0 ) lowerCamelCase_ = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(raw_audio=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , start_step=5 , steps=10 ) lowerCamelCase_ = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 lowerCamelCase_ = self.dummy_unet_condition lowerCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=SCREAMING_SNAKE_CASE_ , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) np.random.seed(0 ) lowerCamelCase_ = torch.rand((1, 1, 10) ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , encoding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.images[0] lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = torch_device lowerCamelCase_ = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
42
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __UpperCamelCase ) -> bool: lowerCamelCase_ = str(__UpperCamelCase ) return len(__UpperCamelCase ) == 9 and set(__UpperCamelCase ) == set('123456789' ) def _UpperCamelCase ( ) -> int | None: for base_num in range(99_99 ,49_99 ,-1 ): lowerCamelCase_ = 10_00_02 * base_num if is_9_pandigital(__UpperCamelCase ): return candidate for base_num in range(3_33 ,99 ,-1 ): lowerCamelCase_ = 1_00_20_03 * base_num if is_9_pandigital(__UpperCamelCase ): return candidate return None if __name__ == "__main__": print(f'''{solution() = }''')
42
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = IFInpaintingSuperResolutionPipeline SCREAMING_SNAKE_CASE_ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'} SCREAMING_SNAKE_CASE_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'original_image'} ) SCREAMING_SNAKE_CASE_ = PipelineTesterMixin.required_optional_params - {'latents'} def UpperCamelCase( self ) -> Tuple: '''simple docstring''' return self._get_superresolution_dummy_components() def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ) -> int: '''simple docstring''' if str(SCREAMING_SNAKE_CASE_ ).startswith('mps' ): lowerCamelCase_ = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = floats_tensor((1, 3, 16, 16) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'original_image': original_image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def UpperCamelCase( self ) -> str: '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != 'cuda' , reason='float16 requires CUDA' ) def UpperCamelCase( self ) -> Any: '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def UpperCamelCase( self ) -> str: '''simple docstring''' self._test_save_load_local() def UpperCamelCase( self ) -> Any: '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
42
'''simple docstring''' A_ = "Input must be a string of 8 numbers plus letter" A_ = "TRWAGMYFPDXBNJZSQVHLCKE" def _UpperCamelCase ( __UpperCamelCase ) -> bool: if not isinstance(__UpperCamelCase ,__UpperCamelCase ): lowerCamelCase_ = f'''Expected string as input, found {type(__UpperCamelCase ).__name__}''' raise TypeError(__UpperCamelCase ) lowerCamelCase_ = spanish_id.replace('-' ,'' ).upper() if len(__UpperCamelCase ) != 9: raise ValueError(__UpperCamelCase ) try: lowerCamelCase_ = int(spanish_id_clean[0:8] ) lowerCamelCase_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(__UpperCamelCase ) from ex if letter.isdigit(): raise ValueError(__UpperCamelCase ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
42
1
'''simple docstring''' from math import pow, sqrt def _UpperCamelCase ( *__UpperCamelCase ) -> bool: lowerCamelCase_ = len(__UpperCamelCase ) > 0 and all(value > 0.0 for value in values ) return result def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> float | ValueError: return ( round(sqrt(molar_mass_a / molar_mass_a ) ,6 ) if validate(__UpperCamelCase ,__UpperCamelCase ) else ValueError('Input Error: Molar mass values must greater than 0.' ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> float | ValueError: return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) ,6 ) if validate(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> float | ValueError: return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) ,6 ) if validate(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> float | ValueError: return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a ,2 ) ,6 ) if validate(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> float | ValueError: return ( round(pow(effusion_rate_a / effusion_rate_a ,2 ) / molar_mass ,6 ) if validate(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) )
42
'''simple docstring''' import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = GPTSanJapaneseTokenizer SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = {'do_clean_text': False, 'add_prefix_space': False} def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' super().setUp() # fmt: off lowerCamelCase_ = ['こん', 'こんに', 'にちは', 'ばんは', '世界,㔺界', '、', '。', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on lowerCamelCase_ = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # 😀 lowerCamelCase_ = {'unk_token': '<unk>'} lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、世界。😀' return input_text, output_text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.get_input_output_texts(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ ) return text, ids def UpperCamelCase( self ) -> Tuple: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。 こんばんは、㔺界。' lowerCamelCase_ = ['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。'] lowerCamelCase_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids without special tokens lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids with special tokens lowerCamelCase_ = tokens + [tokenizer.unk_token] lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。' lowerCamelCase_ = 'こんにちは、、、、世界。こんばんは、、、、世界。' lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。こんばんは、世界。😀' lowerCamelCase_ = tokenizer.encode(prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode('' , prefix_text=prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = [1] + [0] * (len_prefix + len_text + 1) lowerCamelCase_ = [1] * (len_prefix + len_text + 1) + [0] lowerCamelCase_ = [1] + [1] * (len_prefix) + [0] * (len_text + 1) lowerCamelCase_ = tokenizer(prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = tokenizer.encode('あンいワ' ) lowerCamelCase_ = tokenizer.encode('' , prefix_text='あンいワ' ) lowerCamelCase_ = tokenizer.encode('いワ' , prefix_text='あン' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = [['武田信玄', 'は、'], ['織田信長', 'の配下の、']] lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) # fmt: off lowerCamelCase_ = [[35993, 8640, 25948, 35998, 30647, 35675, 35999, 35999], [35993, 10382, 9868, 35998, 30646, 9459, 30646, 35675]] lowerCamelCase_ = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] lowerCamelCase_ = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass
42
1
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> List[Any]: lowerCamelCase_ = '' for i in table: res += inp[i - 1] return res def _UpperCamelCase ( __UpperCamelCase ) -> Tuple: return data[1:] + data[0] def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> List[Any]: lowerCamelCase_ = '' for i in range(len(__UpperCamelCase ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: lowerCamelCase_ = int('0b' + data[0] + data[-1] ,2 ) lowerCamelCase_ = int('0b' + data[1:3] ,2 ) return bin(s[row][col] )[2:] def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> int: lowerCamelCase_ = message[:4] lowerCamelCase_ = message[4:] lowerCamelCase_ = apply_table(__UpperCamelCase ,__UpperCamelCase ) lowerCamelCase_ = xor(__UpperCamelCase ,__UpperCamelCase ) lowerCamelCase_ = apply_sbox(__UpperCamelCase ,temp[:4] ) # noqa: E741 lowerCamelCase_ = apply_sbox(__UpperCamelCase ,temp[4:] ) lowerCamelCase_ = '0' * (2 - len(__UpperCamelCase )) + l # noqa: E741 lowerCamelCase_ = '0' * (2 - len(__UpperCamelCase )) + r lowerCamelCase_ = apply_table(l + r ,__UpperCamelCase ) lowerCamelCase_ = xor(__UpperCamelCase ,__UpperCamelCase ) return temp + right if __name__ == "__main__": A_ = input("Enter 10 bit key: ") A_ = input("Enter 8 bit message: ") A_ = [6, 3, 7, 4, 8, 5, 10, 9] A_ = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] A_ = [2, 4, 3, 1] A_ = [2, 6, 3, 1, 4, 8, 5, 7] A_ = [4, 1, 3, 5, 7, 2, 8, 6] A_ = [4, 1, 2, 3, 2, 3, 4, 1] A_ = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] A_ = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation A_ = apply_table(key, paa_table) A_ = temp[:5] A_ = temp[5:] A_ = left_shift(left) A_ = left_shift(right) A_ = apply_table(left + right, pa_table) A_ = left_shift(left) A_ = left_shift(right) A_ = left_shift(left) A_ = left_shift(right) A_ = apply_table(left + right, pa_table) # encryption A_ = apply_table(message, IP) A_ = function(expansion, sa, sa, keya, temp) A_ = temp[4:] + temp[:4] A_ = function(expansion, sa, sa, keya, temp) A_ = apply_table(temp, IP_inv) print("Cipher text is:", CT) # decryption A_ = apply_table(CT, IP) A_ = function(expansion, sa, sa, keya, temp) A_ = temp[4:] + temp[:4] A_ = function(expansion, sa, sa, keya, temp) A_ = apply_table(temp, IP_inv) print("Plain text after decypting is:", PT)
42
'''simple docstring''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Dict: '''simple docstring''' super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> List[str]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory lowerCamelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> List[str]: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}''' ) 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 (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(SCREAMING_SNAKE_CASE_ )}.''' ) # get prompt text embeddings lowerCamelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=self.tokenizer.model_max_length , return_tensors='pt' , ) lowerCamelCase_ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowerCamelCase_ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( 'The following part of your input was truncated because CLIP can only handle sequences up to' f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) lowerCamelCase_ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: lowerCamelCase_ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = text_embeddings.shape lowerCamelCase_ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) lowerCamelCase_ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # 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. lowerCamelCase_ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: lowerCamelCase_ = 42 if negative_prompt is None: lowerCamelCase_ = [''] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( f'''`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=''' f''' {type(SCREAMING_SNAKE_CASE_ )}.''' ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( f'''`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:''' f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' ' the batch size of `prompt`.' ) else: lowerCamelCase_ = negative_prompt lowerCamelCase_ = text_input_ids.shape[-1] lowerCamelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='pt' , ) lowerCamelCase_ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCamelCase_ = uncond_embeddings.shape[1] lowerCamelCase_ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) lowerCamelCase_ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCamelCase_ = 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`. lowerCamelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) lowerCamelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) lowerCamelCase_ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps lowerCamelCase_ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='cpu' , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) lowerCamelCase_ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='cpu' , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: lowerCamelCase_ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) lowerCamelCase_ = latents_reference.to(self.device ) lowerCamelCase_ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images lowerCamelCase_ = (latents_shape[3] - latents_shape_reference[3]) // 2 lowerCamelCase_ = (latents_shape[2] - latents_shape_reference[2]) // 2 lowerCamelCase_ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx lowerCamelCase_ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy lowerCamelCase_ = 0 if dx < 0 else dx lowerCamelCase_ = 0 if dy < 0 else dy lowerCamelCase_ = max(-dx , 0 ) lowerCamelCase_ = max(-dy , 0 ) # import pdb # pdb.set_trace() lowerCamelCase_ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand lowerCamelCase_ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ = 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] lowerCamelCase_ = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ = {} if accepts_eta: lowerCamelCase_ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance lowerCamelCase_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCamelCase_ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual lowerCamelCase_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: lowerCamelCase_ ,lowerCamelCase_ = noise_pred.chunk(2 ) lowerCamelCase_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 1 / 0.18_215 * latents lowerCamelCase_ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample lowerCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: lowerCamelCase_ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors='pt' ).to( self.device ) lowerCamelCase_ ,lowerCamelCase_ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: lowerCamelCase_ = None if output_type == "pil": lowerCamelCase_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
42
1
'''simple docstring''' A_ = [0, 2, 4, 6, 8] A_ = [1, 3, 5, 7, 9] def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> int: if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1 ,-1 ,-1 ): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 lowerCamelCase_ = 0 for digit in range(10 ): lowerCamelCase_ = digit result += reversible_numbers( 0 ,(remainder + 2 * digit) // 10 ,__UpperCamelCase ,__UpperCamelCase ) return result lowerCamelCase_ = 0 for digita in range(10 ): lowerCamelCase_ = digita if (remainder + digita) % 2 == 0: lowerCamelCase_ = ODD_DIGITS else: lowerCamelCase_ = EVEN_DIGITS for digita in other_parity_digits: lowerCamelCase_ = digita result += reversible_numbers( remaining_length - 2 ,(remainder + digita + digita) // 10 ,__UpperCamelCase ,__UpperCamelCase ,) return result def _UpperCamelCase ( __UpperCamelCase = 9 ) -> int: lowerCamelCase_ = 0 for length in range(1 ,max_power + 1 ): result += reversible_numbers(__UpperCamelCase ,0 ,[0] * length ,__UpperCamelCase ) return result if __name__ == "__main__": print(f'''{solution() = }''')
42
'''simple docstring''' import pprint import requests A_ = "https://zenquotes.io/api" def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/today' ).json() def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": A_ = random_quotes() pprint.pprint(response)
42
1
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=[10, 20, 30, 40] , SCREAMING_SNAKE_CASE_=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="relu" , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=None , ) -> str: '''simple docstring''' lowerCamelCase_ = parent lowerCamelCase_ = batch_size lowerCamelCase_ = image_size lowerCamelCase_ = num_channels lowerCamelCase_ = embeddings_size lowerCamelCase_ = hidden_sizes lowerCamelCase_ = depths lowerCamelCase_ = is_training lowerCamelCase_ = use_labels lowerCamelCase_ = hidden_act lowerCamelCase_ = num_labels lowerCamelCase_ = scope lowerCamelCase_ = len(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ = None if self.use_labels: lowerCamelCase_ = ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase_ = self.get_config() return config, pixel_values, labels def UpperCamelCase( self ) -> str: '''simple docstring''' return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = TFResNetModel(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.num_labels lowerCamelCase_ = TFResNetForImageClassification(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.prepare_config_and_inputs() lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = config_and_inputs lowerCamelCase_ = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () SCREAMING_SNAKE_CASE_ = ( {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification} if is_tf_available() else {} ) SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = TFResNetModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' return @unittest.skip(reason='ResNet does not use inputs_embeds' ) def UpperCamelCase( self ) -> str: '''simple docstring''' pass @unittest.skip(reason='ResNet does not support input and output embeddings' ) def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' pass def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ = model_class(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ = [*signature.parameters.keys()] lowerCamelCase_ = ['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' def check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = model_class(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ = self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCamelCase_ ,lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: lowerCamelCase_ = layer_type lowerCamelCase_ = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> str: '''simple docstring''' for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ = TFResNetModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase ( ) -> Dict: lowerCamelCase_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase( self ) -> str: '''simple docstring''' return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) lowerCamelCase_ = self.default_image_processor lowerCamelCase_ = prepare_img() lowerCamelCase_ = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='tf' ) # forward pass lowerCamelCase_ = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits lowerCamelCase_ = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tf.constant([-11.1_069, -9.7_877, -8.3_777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
42
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=33 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ) -> int: '''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_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = num_attention_heads lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = type_vocab_size lowerCamelCase_ = type_sequence_label_size lowerCamelCase_ = initializer_range lowerCamelCase_ = num_labels lowerCamelCase_ = num_choices lowerCamelCase_ = scope def UpperCamelCase( self ) -> str: '''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 lowerCamelCase_ = None lowerCamelCase_ = None if self.use_labels: lowerCamelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase_ = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase_ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase( self ) -> List[str]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = EsmModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = EsmForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' lowerCamelCase_ = self.num_labels lowerCamelCase_ = EsmForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) = config_and_inputs lowerCamelCase_ = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ = () SCREAMING_SNAKE_CASE_ = ( { 'feature-extraction': EsmModel, 'fill-mask': EsmForMaskedLM, 'text-classification': EsmForSequenceClassification, 'token-classification': EsmForTokenClassification, 'zero-shot': EsmForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = EsmModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> str: '''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(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ = EsmModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()[0] lowerCamelCase_ = EsmEmbeddings(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) lowerCamelCase_ = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) lowerCamelCase_ = create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE_ , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()[0] lowerCamelCase_ = EsmEmbeddings(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.empty(2 , 4 , 30 ) lowerCamelCase_ = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] lowerCamelCase_ = torch.as_tensor([expected_single_positions, expected_single_positions] ) lowerCamelCase_ = embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE_ ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) @unittest.skip('Esm does not support embedding resizing' ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' pass @unittest.skip('Esm does not support embedding resizing' ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass @require_torch class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' with torch.no_grad(): lowerCamelCase_ = EsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() lowerCamelCase_ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )[0] lowerCamelCase_ = 33 lowerCamelCase_ = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCamelCase( self ) -> Tuple: '''simple docstring''' with torch.no_grad(): lowerCamelCase_ = EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() lowerCamelCase_ = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )[0] # compare the actual values for a slice. lowerCamelCase_ = torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
42
1
'''simple docstring''' import sys def _UpperCamelCase ( __UpperCamelCase ) -> Optional[Any]: lowerCamelCase_ = len(__UpperCamelCase ) lowerCamelCase_ = [[0 for x in range(__UpperCamelCase )] for x in range(__UpperCamelCase )] lowerCamelCase_ = [[0 for x in range(__UpperCamelCase )] for x in range(__UpperCamelCase )] for chain_length in range(2 ,__UpperCamelCase ): for a in range(1 ,n - chain_length + 1 ): lowerCamelCase_ = a + chain_length - 1 lowerCamelCase_ = sys.maxsize for c in range(__UpperCamelCase ,__UpperCamelCase ): lowerCamelCase_ = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: lowerCamelCase_ = cost lowerCamelCase_ = c return matrix, sol def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Optional[int]: if i == j: print('A' + str(__UpperCamelCase ) ,end=' ' ) else: print('(' ,end=' ' ) print_optiomal_solution(__UpperCamelCase ,__UpperCamelCase ,optimal_solution[i][j] ) print_optiomal_solution(__UpperCamelCase ,optimal_solution[i][j] + 1 ,__UpperCamelCase ) print(')' ,end=' ' ) def _UpperCamelCase ( ) -> Optional[int]: lowerCamelCase_ = [30, 35, 15, 5, 10, 20, 25] lowerCamelCase_ = len(__UpperCamelCase ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 lowerCamelCase_ ,lowerCamelCase_ = matrix_chain_order(__UpperCamelCase ) print('No. of Operation required: ' + str(matrix[1][n - 1] ) ) print_optiomal_solution(__UpperCamelCase ,1 ,n - 1 ) if __name__ == "__main__": main()
42
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A_ = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
42
1
'''simple docstring''' import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class UpperCAmelCase ( pl.LightningModule ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' super().__init__() lowerCamelCase_ = model lowerCamelCase_ = 2 lowerCamelCase_ = nn.Linear(self.model.config.hidden_size , self.num_labels ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' pass def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> int: # load longformer model from model identifier lowerCamelCase_ = LongformerModel.from_pretrained(__UpperCamelCase ) lowerCamelCase_ = LightningModel(__UpperCamelCase ) lowerCamelCase_ = torch.load(__UpperCamelCase ,map_location=torch.device('cpu' ) ) lightning_model.load_state_dict(ckpt['state_dict'] ) # init longformer question answering model lowerCamelCase_ = LongformerForQuestionAnswering.from_pretrained(__UpperCamelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(__UpperCamelCase ) print(f'''Conversion successful. Model saved under {pytorch_dump_folder_path}''' ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--longformer_model", default=None, type=str, required=True, help="model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.", ) parser.add_argument( "--longformer_question_answering_ckpt_path", default=None, type=str, required=True, help="Path the official PyTorch Lightning Checkpoint.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) A_ = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
42
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json" ), } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'xlm-prophetnet' SCREAMING_SNAKE_CASE_ = ['past_key_values'] SCREAMING_SNAKE_CASE_ = { 'num_attention_heads': 'num_encoder_attention_heads', } def __init__( self , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = "gelu" , SCREAMING_SNAKE_CASE_ = 30522 , SCREAMING_SNAKE_CASE_ = 1024 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 2 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 128 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 2 , **SCREAMING_SNAKE_CASE_ , ) -> Tuple: '''simple docstring''' lowerCamelCase_ = vocab_size lowerCamelCase_ = hidden_size lowerCamelCase_ = encoder_ffn_dim lowerCamelCase_ = num_encoder_layers lowerCamelCase_ = num_encoder_attention_heads lowerCamelCase_ = decoder_ffn_dim lowerCamelCase_ = num_decoder_layers lowerCamelCase_ = num_decoder_attention_heads lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = init_std # Normal(0, this parameter) lowerCamelCase_ = activation_function # parameters for xlmprophetnet lowerCamelCase_ = ngram lowerCamelCase_ = num_buckets lowerCamelCase_ = relative_max_distance lowerCamelCase_ = disable_ngram_loss lowerCamelCase_ = eps # 3 Types of Dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = dropout lowerCamelCase_ = use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , add_cross_attention=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @property def UpperCamelCase( self ) -> int: '''simple docstring''' return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' raise NotImplementedError( 'This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and' ' `num_decoder_layers`.' )
42
1
'''simple docstring''' from __future__ import annotations import math A_ = "2020.9.26" A_ = "xcodz-dot, cclaus, dhruvmanila" def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> tuple[float, float]: if not all(isinstance(__UpperCamelCase ,(float, int) ) for val in locals().values() ): lowerCamelCase_ = f'''Input values must either be float or int: {list(locals().values() )}''' raise TypeError(__UpperCamelCase ) lowerCamelCase_ = ((x * distance) / (z + distance)) * scale lowerCamelCase_ = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> tuple[float, float, float]: if not isinstance(__UpperCamelCase ,__UpperCamelCase ): raise TypeError('Axis must be a str' ) lowerCamelCase_ = locals() del input_variables["axis"] if not all(isinstance(__UpperCamelCase ,(float, int) ) for val in input_variables.values() ): lowerCamelCase_ = ( 'Input values except axis must either be float or int: ' f'''{list(input_variables.values() )}''' ) raise TypeError(__UpperCamelCase ) lowerCamelCase_ = (angle % 3_60) / 4_50 * 1_80 / math.pi if axis == "z": lowerCamelCase_ = x * math.cos(__UpperCamelCase ) - y * math.sin(__UpperCamelCase ) lowerCamelCase_ = y * math.cos(__UpperCamelCase ) + x * math.sin(__UpperCamelCase ) lowerCamelCase_ = z elif axis == "x": lowerCamelCase_ = y * math.cos(__UpperCamelCase ) - z * math.sin(__UpperCamelCase ) lowerCamelCase_ = z * math.cos(__UpperCamelCase ) + y * math.sin(__UpperCamelCase ) lowerCamelCase_ = x elif axis == "y": lowerCamelCase_ = x * math.cos(__UpperCamelCase ) - z * math.sin(__UpperCamelCase ) lowerCamelCase_ = z * math.cos(__UpperCamelCase ) + x * math.sin(__UpperCamelCase ) lowerCamelCase_ = y else: raise ValueError('not a valid axis, choose one of \'x\', \'y\', \'z\'' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(f'''{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }''') print(f'''{rotate(1.0, 2.0, 3.0, "y", 90.0) = }''')
42
'''simple docstring''' import colorsys from PIL import Image # type: ignore def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> float: lowerCamelCase_ = x lowerCamelCase_ = y for step in range(__UpperCamelCase ): # noqa: B007 lowerCamelCase_ = a * a - b * b + x lowerCamelCase_ = 2 * a * b + y lowerCamelCase_ = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _UpperCamelCase ( __UpperCamelCase ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _UpperCamelCase ( __UpperCamelCase ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(__UpperCamelCase ,1 ,1 ) ) def _UpperCamelCase ( __UpperCamelCase = 8_00 ,__UpperCamelCase = 6_00 ,__UpperCamelCase = -0.6 ,__UpperCamelCase = 0 ,__UpperCamelCase = 3.2 ,__UpperCamelCase = 50 ,__UpperCamelCase = True ,) -> Image.Image: lowerCamelCase_ = Image.new('RGB' ,(image_width, image_height) ) lowerCamelCase_ = img.load() # loop through the image-coordinates for image_x in range(__UpperCamelCase ): for image_y in range(__UpperCamelCase ): # determine the figure-coordinates based on the image-coordinates lowerCamelCase_ = figure_width / image_width * image_height lowerCamelCase_ = figure_center_x + (image_x / image_width - 0.5) * figure_width lowerCamelCase_ = figure_center_y + (image_y / image_height - 0.5) * figure_height lowerCamelCase_ = get_distance(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: lowerCamelCase_ = get_color_coded_rgb(__UpperCamelCase ) else: lowerCamelCase_ = get_black_and_white_rgb(__UpperCamelCase ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure A_ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
42
1
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging A_ = logging.get_logger(__name__) A_ = { "deepmind/language-perceiver": "https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json", # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'perceiver' def __init__( self , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=1280 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=26 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="kv" , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1E-12 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=262 , SCREAMING_SNAKE_CASE_=2048 , SCREAMING_SNAKE_CASE_=56 , SCREAMING_SNAKE_CASE_=[368, 496] , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=1920 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=[1, 16, 224, 224] , **SCREAMING_SNAKE_CASE_ , ) -> Optional[int]: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = num_latents lowerCamelCase_ = d_latents lowerCamelCase_ = d_model lowerCamelCase_ = num_blocks lowerCamelCase_ = num_self_attends_per_block lowerCamelCase_ = num_self_attention_heads lowerCamelCase_ = num_cross_attention_heads lowerCamelCase_ = qk_channels lowerCamelCase_ = v_channels lowerCamelCase_ = cross_attention_shape_for_attention lowerCamelCase_ = self_attention_widening_factor lowerCamelCase_ = cross_attention_widening_factor lowerCamelCase_ = hidden_act lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = initializer_range lowerCamelCase_ = layer_norm_eps lowerCamelCase_ = use_query_residual # masked language modeling attributes lowerCamelCase_ = vocab_size lowerCamelCase_ = max_position_embeddings # image classification attributes lowerCamelCase_ = image_size # flow attributes lowerCamelCase_ = train_size # multimodal autoencoding attributes lowerCamelCase_ = num_frames lowerCamelCase_ = audio_samples_per_frame lowerCamelCase_ = samples_per_patch lowerCamelCase_ = output_shape class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' @property def UpperCamelCase( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": lowerCamelCase_ = {0: 'batch', 1: 'choice', 2: 'sequence'} else: lowerCamelCase_ = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('inputs', dynamic_axis), ('attention_mask', dynamic_axis), ] ) @property def UpperCamelCase( self ) -> float: '''simple docstring''' return 1E-4 def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = -1 , SCREAMING_SNAKE_CASE_ = -1 , SCREAMING_SNAKE_CASE_ = -1 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 3 , SCREAMING_SNAKE_CASE_ = 40 , SCREAMING_SNAKE_CASE_ = 40 , ) -> Mapping[str, Any]: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX lowerCamelCase_ = compute_effective_axis_dimension( SCREAMING_SNAKE_CASE_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX lowerCamelCase_ = preprocessor.num_special_tokens_to_add(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = compute_effective_axis_dimension( SCREAMING_SNAKE_CASE_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=SCREAMING_SNAKE_CASE_ ) # Generate dummy inputs according to compute batch and sequence lowerCamelCase_ = [' '.join(['a'] ) * seq_length] * batch_size lowerCamelCase_ = dict(preprocessor(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase_ = inputs.pop('input_ids' ) return inputs elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX lowerCamelCase_ = compute_effective_axis_dimension(SCREAMING_SNAKE_CASE_ , fixed_dimension=OnnxConfig.default_fixed_batch ) lowerCamelCase_ = self._generate_dummy_images(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = dict(preprocessor(images=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase_ = inputs.pop('pixel_values' ) return inputs else: raise ValueError( 'Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.' )
42
'''simple docstring''' from math import isclose, sqrt def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> tuple[float, float, float]: lowerCamelCase_ = point_y / 4 / point_x lowerCamelCase_ = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) lowerCamelCase_ = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) lowerCamelCase_ = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 lowerCamelCase_ = outgoing_gradient**2 + 4 lowerCamelCase_ = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) lowerCamelCase_ = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 lowerCamelCase_ = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) lowerCamelCase_ = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point lowerCamelCase_ = x_minus if isclose(__UpperCamelCase ,__UpperCamelCase ) else x_plus lowerCamelCase_ = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _UpperCamelCase ( __UpperCamelCase = 1.4 ,__UpperCamelCase = -9.6 ) -> int: lowerCamelCase_ = 0 lowerCamelCase_ = first_x_coord lowerCamelCase_ = first_y_coord lowerCamelCase_ = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = next_point(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
42
1
'''simple docstring''' from collections import namedtuple A_ = namedtuple("from_to", "from_ to") A_ = { "cubicmeter": from_to(1, 1), "litre": from_to(0.001, 1_000), "kilolitre": from_to(1, 1), "gallon": from_to(0.00_454, 264.172), "cubicyard": from_to(0.76_455, 1.30_795), "cubicfoot": from_to(0.028, 35.3_147), "cup": from_to(0.000_236_588, 4_226.75), } def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( f'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ', '.join(__UpperCamelCase ) ) if to_type not in METRIC_CONVERSION: raise ValueError( f'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ', '.join(__UpperCamelCase ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
42
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = False ) -> bool: if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3_31_70_44_06_46_79_88_73_85_96_19_81 and not allow_probable: raise ValueError( 'Warning: upper bound of deterministic test is exceeded. ' 'Pass allow_probable=True to allow probabilistic test. ' 'A return value of True indicates a probable prime.' ) # array bounds provided by analysis lowerCamelCase_ = [ 20_47, 1_37_36_53, 25_32_60_01, 32_15_03_17_51, 2_15_23_02_89_87_47, 3_47_47_49_66_03_83, 3_41_55_00_71_72_83_21, 1, 3_82_51_23_05_65_46_41_30_51, 1, 1, 31_86_65_85_78_34_03_11_51_16_74_61, 3_31_70_44_06_46_79_88_73_85_96_19_81, ] lowerCamelCase_ = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(__UpperCamelCase ,1 ): if n < _p: # then we have our last prime to check lowerCamelCase_ = primes[:idx] break lowerCamelCase_ ,lowerCamelCase_ = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: lowerCamelCase_ = False for r in range(__UpperCamelCase ): lowerCamelCase_ = pow(__UpperCamelCase ,d * 2**r ,__UpperCamelCase ) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): lowerCamelCase_ = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True def _UpperCamelCase ( ) -> None: assert not miller_rabin(5_61 ) assert miller_rabin(5_63 ) # 2047 assert not miller_rabin(83_82_01 ) assert miller_rabin(83_82_07 ) # 1_373_653 assert not miller_rabin(17_31_60_01 ) assert miller_rabin(17_31_60_17 ) # 25_326_001 assert not miller_rabin(30_78_38_66_41 ) assert miller_rabin(30_78_38_66_53 ) # 3_215_031_751 assert not miller_rabin(1_71_30_45_57_48_01 ) assert miller_rabin(1_71_30_45_57_48_19 ) # 2_152_302_898_747 assert not miller_rabin(2_77_97_99_72_83_07 ) assert miller_rabin(2_77_97_99_72_83_27 ) # 3_474_749_660_383 assert not miller_rabin(1_13_85_00_23_90_94_41 ) assert miller_rabin(1_13_85_00_23_90_95_27 ) # 341_550_071_728_321 assert not miller_rabin(1_27_50_41_01_88_48_80_43_51 ) assert miller_rabin(1_27_50_41_01_88_48_80_43_91 ) # 3_825_123_056_546_413_051 assert not miller_rabin(7_96_66_46_44_58_50_77_87_79_18_67 ) assert miller_rabin(7_96_66_46_44_58_50_77_87_79_19_51 ) # 318_665_857_834_031_151_167_461 assert not miller_rabin(55_28_40_67_74_46_64_78_97_66_03_33 ) assert miller_rabin(55_28_40_67_74_46_64_78_97_66_03_59 ) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
42
1
'''simple docstring''' from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = 1.0 if scale is None else scale lowerCamelCase_ = 0.0 if loc is None else loc super().__init__(SCREAMING_SNAKE_CASE_ , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=SCREAMING_SNAKE_CASE_ )] ) @property def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' return self.base_dist.mean * self.scale + self.loc @property def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' return self.base_dist.variance * self.scale**2 @property def UpperCamelCase( self ) -> List[str]: '''simple docstring''' return self.variance.sqrt() class UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = args_dim lowerCamelCase_ = nn.ModuleList([nn.Linear(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for dim in args_dim.values()] ) lowerCamelCase_ = domain_map def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple[torch.Tensor]: '''simple docstring''' lowerCamelCase_ = [proj(SCREAMING_SNAKE_CASE_ ) for proj in self.proj] return self.domain_map(*SCREAMING_SNAKE_CASE_ ) class UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' super().__init__() lowerCamelCase_ = function def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' return self.function(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ) class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 def __init__( self , SCREAMING_SNAKE_CASE_ = 1 ) -> None: '''simple docstring''' lowerCamelCase_ = dim lowerCamelCase_ = {k: dim * self.args_dim[k] for k in self.args_dim} def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' if self.dim == 1: return self.distribution_class(*SCREAMING_SNAKE_CASE_ ) else: return Independent(self.distribution_class(*SCREAMING_SNAKE_CASE_ ) , 1 ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ) -> Distribution: '''simple docstring''' lowerCamelCase_ = self._base_distribution(SCREAMING_SNAKE_CASE_ ) if loc is None and scale is None: return distr else: return AffineTransformed(SCREAMING_SNAKE_CASE_ , loc=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , event_dim=self.event_dim ) @property def UpperCamelCase( self ) -> Tuple: '''simple docstring''' return () if self.dim == 1 else (self.dim,) @property def UpperCamelCase( self ) -> int: '''simple docstring''' return len(self.event_shape ) @property def UpperCamelCase( self ) -> float: '''simple docstring''' return 0.0 def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> nn.Module: '''simple docstring''' return ParameterProjection( in_features=SCREAMING_SNAKE_CASE_ , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def UpperCamelCase( self , *SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError() @staticmethod def UpperCamelCase( SCREAMING_SNAKE_CASE_ ) -> torch.Tensor: '''simple docstring''' return (x + torch.sqrt(torch.square(SCREAMING_SNAKE_CASE_ ) + 4.0 )) / 2.0 class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = {"df": 1, "loc": 1, "scale": 1} SCREAMING_SNAKE_CASE_ = StudentT @classmethod def UpperCamelCase( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' lowerCamelCase_ = cls.squareplus(SCREAMING_SNAKE_CASE_ ).clamp_min(torch.finfo(scale.dtype ).eps ) lowerCamelCase_ = 2.0 + cls.squareplus(SCREAMING_SNAKE_CASE_ ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = {"loc": 1, "scale": 1} SCREAMING_SNAKE_CASE_ = Normal @classmethod def UpperCamelCase( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' lowerCamelCase_ = cls.squareplus(SCREAMING_SNAKE_CASE_ ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = {"total_count": 1, "logits": 1} SCREAMING_SNAKE_CASE_ = NegativeBinomial @classmethod def UpperCamelCase( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' lowerCamelCase_ = cls.squareplus(SCREAMING_SNAKE_CASE_ ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Distribution: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = distr_args if self.dim == 1: return self.distribution_class(total_count=SCREAMING_SNAKE_CASE_ , logits=SCREAMING_SNAKE_CASE_ ) else: return Independent(self.distribution_class(total_count=SCREAMING_SNAKE_CASE_ , logits=SCREAMING_SNAKE_CASE_ ) , 1 ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None ) -> Distribution: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
42
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler A_ = 16 A_ = 32 def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = 16 ,__UpperCamelCase = "bert-base-cased" ) -> List[Any]: lowerCamelCase_ = AutoTokenizer.from_pretrained(__UpperCamelCase ) lowerCamelCase_ = load_dataset('glue' ,'mrpc' ) def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) lowerCamelCase_ = tokenizer(examples['sentence1'] ,examples['sentence2'] ,truncation=__UpperCamelCase ,max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowerCamelCase_ = datasets.map( __UpperCamelCase ,batched=__UpperCamelCase ,remove_columns=['idx', 'sentence1', 'sentence2'] ,load_from_cache_file=__UpperCamelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCamelCase_ = tokenized_datasets.rename_column('label' ,'labels' ) 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. lowerCamelCase_ = DataLoader( tokenized_datasets['train'] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) lowerCamelCase_ = DataLoader( tokenized_datasets['validation'] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Union[str, Any]: model.eval() lowerCamelCase_ = 0 for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times lowerCamelCase_ ,lowerCamelCase_ = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__UpperCamelCase ) - 1: lowerCamelCase_ = predictions[: len(eval_dataloader.dataset ) - samples_seen] lowerCamelCase_ = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__UpperCamelCase ,references=__UpperCamelCase ,) lowerCamelCase_ = metric.compute() return eval_metric["accuracy"] def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> List[str]: # Initialize accelerator lowerCamelCase_ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCamelCase_ = config['lr'] lowerCamelCase_ = int(config['num_epochs'] ) lowerCamelCase_ = int(config['seed'] ) lowerCamelCase_ = int(config['batch_size'] ) lowerCamelCase_ = args.model_name_or_path set_seed(__UpperCamelCase ) lowerCamelCase_ ,lowerCamelCase_ = get_dataloaders(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCamelCase_ = AutoModelForSequenceClassification.from_pretrained(__UpperCamelCase ,return_dict=__UpperCamelCase ) # Instantiate optimizer lowerCamelCase_ = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowerCamelCase_ = optimizer_cls(params=model.parameters() ,lr=__UpperCamelCase ) if accelerator.state.deepspeed_plugin is not None: lowerCamelCase_ = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: lowerCamelCase_ = 1 lowerCamelCase_ = (len(__UpperCamelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowerCamelCase_ = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase ,num_warmup_steps=0 ,num_training_steps=__UpperCamelCase ,) else: lowerCamelCase_ = DummyScheduler(__UpperCamelCase ,total_num_steps=__UpperCamelCase ,warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = accelerator.prepare( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # We need to keep track of how many total steps we have iterated over lowerCamelCase_ = 0 # We also need to keep track of the stating epoch so files are named properly lowerCamelCase_ = 0 lowerCamelCase_ = evaluate.load('glue' ,'mrpc' ) lowerCamelCase_ = num_epochs if args.partial_train_epoch is not None: lowerCamelCase_ = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) lowerCamelCase_ = args.resume_from_checkpoint.split('epoch_' )[1] lowerCamelCase_ = '' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break lowerCamelCase_ = int(__UpperCamelCase ) + 1 lowerCamelCase_ = evaluation_loop(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) accelerator.print('resumed checkpoint performance:' ,__UpperCamelCase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:' ,lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:' ,optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir ,f'''state_{starting_epoch-1}.json''' ) ,'r' ) as f: lowerCamelCase_ = json.load(__UpperCamelCase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model lowerCamelCase_ = {} for epoch in range(__UpperCamelCase ,__UpperCamelCase ): model.train() for step, batch in enumerate(__UpperCamelCase ): lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.loss lowerCamelCase_ = loss / gradient_accumulation_steps accelerator.backward(__UpperCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 lowerCamelCase_ = f'''epoch_{epoch}''' lowerCamelCase_ = os.path.join(args.output_dir ,__UpperCamelCase ) accelerator.save_state(__UpperCamelCase ) lowerCamelCase_ = evaluation_loop(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) lowerCamelCase_ = accuracy lowerCamelCase_ = lr_scheduler.get_lr()[0] lowerCamelCase_ = optimizer.param_groups[0]['lr'] lowerCamelCase_ = epoch lowerCamelCase_ = overall_step accelerator.print(f'''epoch {epoch}:''' ,__UpperCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,f'''state_{epoch}.json''' ) ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( ) -> str: lowerCamelCase_ = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' ,type=__UpperCamelCase ,default='bert-base-cased' ,help='Path to pretrained model or model identifier from huggingface.co/models.' ,required=__UpperCamelCase ,) parser.add_argument( '--output_dir' ,type=__UpperCamelCase ,default='.' ,help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' ,) parser.add_argument( '--resume_from_checkpoint' ,type=__UpperCamelCase ,default=__UpperCamelCase ,help='If the training should continue from a checkpoint folder.' ,) parser.add_argument( '--partial_train_epoch' ,type=__UpperCamelCase ,default=__UpperCamelCase ,help='If passed, the training will stop after this number of epochs.' ,) parser.add_argument( '--num_epochs' ,type=__UpperCamelCase ,default=2 ,help='Number of train epochs.' ,) lowerCamelCase_ = parser.parse_args() lowerCamelCase_ = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(__UpperCamelCase ,__UpperCamelCase ) if __name__ == "__main__": main()
42
1
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase ) -> tuple[int, int]: try: lowerCamelCase_ = float(__UpperCamelCase ) except ValueError: raise ValueError('Please enter a valid number' ) lowerCamelCase_ = decimal - int(__UpperCamelCase ) if fractional_part == 0: return int(__UpperCamelCase ), 1 else: lowerCamelCase_ = len(str(__UpperCamelCase ).split('.' )[1] ) lowerCamelCase_ = int(decimal * (10**number_of_frac_digits) ) lowerCamelCase_ = 10**number_of_frac_digits lowerCamelCase_ ,lowerCamelCase_ = denominator, numerator while True: lowerCamelCase_ = dividend % divisor if remainder == 0: break lowerCamelCase_ ,lowerCamelCase_ = divisor, remainder lowerCamelCase_ ,lowerCamelCase_ = numerator / divisor, denominator / divisor return int(__UpperCamelCase ), int(__UpperCamelCase ) if __name__ == "__main__": print(f'''{decimal_to_fraction(2) = }''') print(f'''{decimal_to_fraction(89.0) = }''') print(f'''{decimal_to_fraction("67") = }''') print(f'''{decimal_to_fraction("45.0") = }''') print(f'''{decimal_to_fraction(1.5) = }''') print(f'''{decimal_to_fraction("6.25") = }''') print(f'''{decimal_to_fraction("78td") = }''')
42
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> np.ndarray: # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: lowerCamelCase_ = ksize + 1 lowerCamelCase_ = np.zeros((ksize, ksize) ,dtype=np.floataa ) # each value for y in range(__UpperCamelCase ): for x in range(__UpperCamelCase ): # distance from center lowerCamelCase_ = x - ksize // 2 lowerCamelCase_ = y - ksize // 2 # degree to radiant lowerCamelCase_ = theta / 1_80 * np.pi lowerCamelCase_ = np.cos(_theta ) lowerCamelCase_ = np.sin(_theta ) # get kernel x lowerCamelCase_ = cos_theta * px + sin_theta * py # get kernel y lowerCamelCase_ = -sin_theta * px + cos_theta * py # fill kernel lowerCamelCase_ = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image A_ = imread("../image_data/lena.jpg") # turn image in gray scale value A_ = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges A_ = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: A_ = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) A_ = out / out.max() * 255 A_ = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
42
1
'''simple docstring''' from __future__ import annotations A_ = 1.6_0_2_1E-1_9 # units = C def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,) -> tuple[str, float]: if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
42
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['transformers', 'torch', 'note_seq'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['transformers', 'torch', 'note_seq'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['transformers', 'torch', 'note_seq'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' requires_backends(cls , ['transformers', 'torch', 'note_seq'] )
42
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' requires_backends(cls , ['flax'] ) class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['flax'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' requires_backends(self , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' requires_backends(cls , ['flax'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['flax'] )
42
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def UpperCamelCase( self ) -> int: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , ) return model @property def UpperCamelCase( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) lowerCamelCase_ = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) lowerCamelCase_ = DDPMScheduler() lowerCamelCase_ = AudioDiffusionPipeline(vqvae=SCREAMING_SNAKE_CASE_ , unet=self.dummy_unet , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , steps=4 ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = output.images[0] lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , steps=4 , return_dict=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 lowerCamelCase_ = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) lowerCamelCase_ = DDIMScheduler() lowerCamelCase_ = self.dummy_vqvae_and_unet lowerCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) np.random.seed(0 ) lowerCamelCase_ = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(raw_audio=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , start_step=5 , steps=10 ) lowerCamelCase_ = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 lowerCamelCase_ = self.dummy_unet_condition lowerCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=SCREAMING_SNAKE_CASE_ , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) np.random.seed(0 ) lowerCamelCase_ = torch.rand((1, 1, 10) ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , encoding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.images[0] lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = torch_device lowerCamelCase_ = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
42
1
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> float: lowerCamelCase_ = u for i in range(1 ,__UpperCamelCase ): lowerCamelCase_ = temp * (u - i) return temp def _UpperCamelCase ( ) -> None: lowerCamelCase_ = int(input('enter the numbers of values: ' ) ) lowerCamelCase_ = [] for _ in range(__UpperCamelCase ): y.append([] ) for i in range(__UpperCamelCase ): for j in range(__UpperCamelCase ): y[i].append(__UpperCamelCase ) lowerCamelCase_ = 0 print('enter the values of parameters in a list: ' ) lowerCamelCase_ = list(map(__UpperCamelCase ,input().split() ) ) print('enter the values of corresponding parameters: ' ) for i in range(__UpperCamelCase ): lowerCamelCase_ = float(input() ) lowerCamelCase_ = int(input('enter the value to interpolate: ' ) ) lowerCamelCase_ = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 ,__UpperCamelCase ): for j in range(n - i ): lowerCamelCase_ = y[j + 1][i - 1] - y[j][i - 1] lowerCamelCase_ = y[0][0] for i in range(1 ,__UpperCamelCase ): summ += (ucal(__UpperCamelCase ,__UpperCamelCase ) * y[0][i]) / math.factorial(__UpperCamelCase ) print(f'''the value at {value} is {summ}''' ) if __name__ == "__main__": main()
42
'''simple docstring''' import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _UpperCamelCase ( __UpperCamelCase = 8 ) -> str: lowerCamelCase_ = ascii_letters + digits + punctuation return "".join(secrets.choice(__UpperCamelCase ) for _ in range(__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(__UpperCamelCase ) lowerCamelCase_ = i // 3 lowerCamelCase_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) lowerCamelCase_ = ( chars_incl + random(__UpperCamelCase ,quotient + remainder ) + random(__UpperCamelCase ,__UpperCamelCase ) + random(__UpperCamelCase ,__UpperCamelCase ) ) lowerCamelCase_ = list(__UpperCamelCase ) shuffle(__UpperCamelCase ) return "".join(__UpperCamelCase ) # random is a generalised function for letters, characters and numbers def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: return "".join(secrets.choice(__UpperCamelCase ) for _ in range(__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Optional[int]: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Tuple: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = 8 ) -> bool: if len(__UpperCamelCase ) < min_length: # Your Password must be at least 8 characters long return False lowerCamelCase_ = any(char in ascii_uppercase for char in password ) lowerCamelCase_ = any(char in ascii_lowercase for char in password ) lowerCamelCase_ = any(char in digits for char in password ) lowerCamelCase_ = 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 _UpperCamelCase ( ) -> Optional[int]: lowerCamelCase_ = int(input('Please indicate the max length of your password: ' ).strip() ) lowerCamelCase_ = input( 'Please indicate the characters that must be in your password: ' ).strip() print('Password generated:' ,password_generator(__UpperCamelCase ) ) print( 'Alternative Password generated:' ,alternative_password_generator(__UpperCamelCase ,__UpperCamelCase ) ,) print('[If you are thinking of using this passsword, You better save it.]' ) if __name__ == "__main__": main()
42
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "RWKV/rwkv-4-169m-pile": "https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json", "RWKV/rwkv-4-430m-pile": "https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json", "RWKV/rwkv-4-1b5-pile": "https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json", "RWKV/rwkv-4-3b-pile": "https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json", "RWKV/rwkv-4-7b-pile": "https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json", "RWKV/rwkv-4-14b-pile": "https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json", "RWKV/rwkv-raven-1b5": "https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json", "RWKV/rwkv-raven-3b": "https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json", "RWKV/rwkv-raven-7b": "https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json", "RWKV/rwkv-raven-14b": "https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json", } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'rwkv' SCREAMING_SNAKE_CASE_ = {'max_position_embeddings': 'context_length'} def __init__( self , SCREAMING_SNAKE_CASE_=50277 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=1E-5 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , **SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = vocab_size lowerCamelCase_ = context_length lowerCamelCase_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = attention_hidden_size if attention_hidden_size is not None else hidden_size lowerCamelCase_ = intermediate_size if intermediate_size is not None else 4 * hidden_size lowerCamelCase_ = layer_norm_epsilon lowerCamelCase_ = rescale_every lowerCamelCase_ = use_cache lowerCamelCase_ = bos_token_id lowerCamelCase_ = eos_token_id super().__init__( tie_word_embeddings=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
42
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 lowerCamelCase_ = test_metrics @require_cpu def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def UpperCamelCase( self ) -> Tuple: '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def UpperCamelCase( self ) -> Any: '''simple docstring''' self.test_metrics.main() @require_multi_gpu def UpperCamelCase( self ) -> Any: '''simple docstring''' print(f'''Found {torch.cuda.device_count()} devices.''' ) lowerCamelCase_ = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() )
42
1
'''simple docstring''' import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin A_ = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.plbart.modeling_plbart import shift_tokens_right A_ = 50_003 A_ = 50_002 @require_sentencepiece @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = PLBartTokenizer SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = False def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase_ = PLBartTokenizer(SCREAMING_SNAKE_CASE_ , language_codes='base' , keep_accents=SCREAMING_SNAKE_CASE_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = PLBartTokenizer(SCREAMING_SNAKE_CASE_ , language_codes='base' , keep_accents=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase_ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) lowerCamelCase_ = tokenizer.vocab_size lowerCamelCase_ = [tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) for x in range(end - 4 , SCREAMING_SNAKE_CASE_ )] self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['__java__', '__python__', '__en_XX__', '<mask>'] ) lowerCamelCase_ = 'java.lang.Exception, python.lang.Exception, javascript, php, ruby, go' lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ ).input_ids self.assertEqual( tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , ) def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = PLBartTokenizer(SCREAMING_SNAKE_CASE_ , language_codes='multi' , keep_accents=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase_ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) lowerCamelCase_ = tokenizer.vocab_size lowerCamelCase_ = [tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) for x in range(end - 7 , SCREAMING_SNAKE_CASE_ )] self.assertListEqual( SCREAMING_SNAKE_CASE_ , ['__java__', '__python__', '__en_XX__', '__javascript__', '__php__', '__ruby__', '__go__'] ) lowerCamelCase_ = 'java.lang.Exception, python.lang.Exception, javascript, php, ruby, go' lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ ).input_ids self.assertEqual( tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'uclanlp/plbart-python-en_XX' SCREAMING_SNAKE_CASE_ = [ 'def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])', 'def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])', ] SCREAMING_SNAKE_CASE_ = [ 'Returns the maximum value of a b c.', 'Sums the values of a b c.', ] SCREAMING_SNAKE_CASE_ = [ 1_34, 54_52, 3_34_60, 3_34_41, 3_34_63, 3_34_65, 3_34_63, 3_34_49, 9_88, 20, 3_34_56, 19, 3_34_56, 7_71, 39, 42_58, 8_89, 33_18, 3_34_41, 3_34_63, 3_34_65, 3_34_63, 3_34_49, 24_71, 2, PYTHON_CODE, ] @classmethod def UpperCamelCase( cls ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = PLBartTokenizer.from_pretrained( cls.checkpoint_name , language_codes='base' , src_lang='python' , tgt_lang='en_XX' ) lowerCamelCase_ = 1 return cls def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['__java__'] , 50001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['__python__'] , 50002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['__en_XX__'] , 50003 ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> str: '''simple docstring''' self.assertIn(SCREAMING_SNAKE_CASE_ , self.tokenizer.all_special_ids ) lowerCamelCase_ = [EN_CODE, 9037, 33442, 57, 752, 153, 14, 56, 18, 9, 2] lowerCamelCase_ = self.tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = ['def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])' * 20] self.assertIsInstance(src_text[0] , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 10 lowerCamelCase_ = self.tokenizer(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', '__java__'] ) , [50004, 50001] ) def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = PLBartTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 self.assertEqual(batch.input_ids[1][-2:].tolist() , [2, PYTHON_CODE] ) self.assertEqual(batch.decoder_input_ids[1][0] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(batch.decoder_input_ids[1][-1] , 2 ) self.assertEqual(batch.labels[1][-2:].tolist() , [2, EN_CODE] ) @require_torch def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 26) , batch.input_ids.shape ) self.assertEqual((2, 26) , batch.attention_mask.shape ) lowerCamelCase_ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, PYTHON_CODE] ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=3 , return_tensors='pt' ) lowerCamelCase_ = self.tokenizer( text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=10 , return_tensors='pt' ) lowerCamelCase_ = targets['input_ids'] lowerCamelCase_ = shift_tokens_right(SCREAMING_SNAKE_CASE_ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='java' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ) , { # A, test, EOS, en_XX 'input_ids': [[150, 242, 2, 50003]], 'attention_mask': [[1, 1, 1, 1]], # java 'forced_bos_token_id': 50001, } , )
42
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True) os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True) os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: if hor == 1_28: lowerCamelCase_ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') lowerCamelCase_ = (32, 1_28, 2_56) lowerCamelCase_ = ('UpResnetBlock1D', 'UpResnetBlock1D') elif hor == 32: lowerCamelCase_ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') lowerCamelCase_ = (32, 64, 1_28, 2_56) lowerCamelCase_ = ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D') lowerCamelCase_ = torch.load(f'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' ) lowerCamelCase_ = model.state_dict() lowerCamelCase_ = { 'down_block_types': down_block_types, 'block_out_channels': block_out_channels, 'up_block_types': up_block_types, 'layers_per_block': 1, 'use_timestep_embedding': True, 'out_block_type': 'OutConv1DBlock', 'norm_num_groups': 8, 'downsample_each_block': False, 'in_channels': 14, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'flip_sin_to_cos': False, 'freq_shift': 1, 'sample_size': 6_55_36, 'mid_block_type': 'MidResTemporalBlock1D', 'act_fn': 'mish', } lowerCamelCase_ = UNetaDModel(**__UpperCamelCase ) print(f'''length of state dict: {len(state_dict.keys() )}''' ) print(f'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) lowerCamelCase_ = dict(zip(model.state_dict().keys() ,hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): lowerCamelCase_ = state_dict.pop(__UpperCamelCase ) hf_value_function.load_state_dict(__UpperCamelCase ) torch.save(hf_value_function.state_dict() ,f'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' ) with open(f'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( ) -> Tuple: lowerCamelCase_ = { 'in_channels': 14, 'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'), 'up_block_types': (), 'out_block_type': 'ValueFunction', 'mid_block_type': 'ValueFunctionMidBlock1D', 'block_out_channels': (32, 64, 1_28, 2_56), 'layers_per_block': 1, 'downsample_each_block': True, 'sample_size': 6_55_36, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'use_timestep_embedding': True, 'flip_sin_to_cos': False, 'freq_shift': 1, 'norm_num_groups': 8, 'act_fn': 'mish', } lowerCamelCase_ = torch.load('/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch' ) lowerCamelCase_ = model lowerCamelCase_ = UNetaDModel(**__UpperCamelCase ) print(f'''length of state dict: {len(state_dict.keys() )}''' ) print(f'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) lowerCamelCase_ = dict(zip(state_dict.keys() ,hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): lowerCamelCase_ = state_dict.pop(__UpperCamelCase ) hf_value_function.load_state_dict(__UpperCamelCase ) torch.save(hf_value_function.state_dict() ,'hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin' ) with open('hub/hopper-medium-v2/value_function/config.json' ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) if __name__ == "__main__": unet(32) # unet(128) value_function()
42
1
'''simple docstring''' from bisect import bisect from itertools import accumulate def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Tuple: lowerCamelCase_ = sorted(zip(__UpperCamelCase ,__UpperCamelCase ) ,key=lambda __UpperCamelCase : x[0] / x[1] ,reverse=__UpperCamelCase ) lowerCamelCase_ ,lowerCamelCase_ = [i[0] for i in r], [i[1] for i in r] lowerCamelCase_ = list(accumulate(__UpperCamelCase ) ) lowerCamelCase_ = bisect(__UpperCamelCase ,__UpperCamelCase ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
42
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, 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 A_ = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A_ = 250_004 A_ = 250_020 @require_sentencepiece @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = MBartTokenizer SCREAMING_SNAKE_CASE_ = MBartTokenizerFast SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase_ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase_ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def UpperCamelCase( self ) -> int: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase_ = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCamelCase_ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) lowerCamelCase_ = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=True lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=False lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'facebook/mbart-large-en-ro' SCREAMING_SNAKE_CASE_ = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] SCREAMING_SNAKE_CASE_ = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] SCREAMING_SNAKE_CASE_ = [82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2, EN_CODE] @classmethod def UpperCamelCase( cls ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) lowerCamelCase_ = 1 return cls def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 250020 ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' self.assertIn(SCREAMING_SNAKE_CASE_ , self.tokenizer.all_special_ids ) lowerCamelCase_ = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] lowerCamelCase_ = self.tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 10 lowerCamelCase_ = self.tokenizer(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [250026, 250001] ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = MBartTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) lowerCamelCase_ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=3 , return_tensors='pt' ) lowerCamelCase_ = self.tokenizer( text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=10 , return_tensors='pt' ) lowerCamelCase_ = targets['input_ids'] lowerCamelCase_ = shift_tokens_right(SCREAMING_SNAKE_CASE_ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ) , { # A, test, EOS, en_XX 'input_ids': [[62, 3034, 2, 250004]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 250001, } , )
42
1
'''simple docstring''' import pprint import requests A_ = "https://zenquotes.io/api" def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/today' ).json() def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": A_ = random_quotes() pprint.pprint(response)
42
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = 'ylacombe/bark-small' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = 'en_speaker_1' lowerCamelCase_ = 'This is a test string' lowerCamelCase_ = 'speaker_embeddings_path.json' lowerCamelCase_ = 'speaker_embeddings' def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase_ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase_ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCamelCase_ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='(BOS)' , eos_token='(EOS)' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase_ = 35 lowerCamelCase_ = 2 lowerCamelCase_ = 8 lowerCamelCase_ = { 'semantic_prompt': np.ones(SCREAMING_SNAKE_CASE_ ), 'coarse_prompt': np.ones((nb_codebooks_coarse, seq_len) ), 'fine_prompt': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() ) # test loading voice preset from npz file lowerCamelCase_ = os.path.join(self.tmpdirname , 'file.npz' ) np.savez(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() ) # test loading voice preset from the hub lowerCamelCase_ = processor(text=self.input_string , voice_preset=self.voice_preset ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = processor(text=self.input_string ) lowerCamelCase_ = tokenizer( self.input_string , padding='max_length' , max_length=256 , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
42
1
'''simple docstring''' import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger() def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase = True ) -> List[str]: print(f'''Converting {name}...''' ) with torch.no_grad(): if hidden_sizes == 1_28: if name[-1] == "S": lowerCamelCase_ = timm.create_model('levit_128s' ,pretrained=__UpperCamelCase ) else: lowerCamelCase_ = timm.create_model('levit_128' ,pretrained=__UpperCamelCase ) if hidden_sizes == 1_92: lowerCamelCase_ = timm.create_model('levit_192' ,pretrained=__UpperCamelCase ) if hidden_sizes == 2_56: lowerCamelCase_ = timm.create_model('levit_256' ,pretrained=__UpperCamelCase ) if hidden_sizes == 3_84: lowerCamelCase_ = timm.create_model('levit_384' ,pretrained=__UpperCamelCase ) from_model.eval() lowerCamelCase_ = LevitForImageClassificationWithTeacher(__UpperCamelCase ).eval() lowerCamelCase_ = OrderedDict() lowerCamelCase_ = from_model.state_dict() lowerCamelCase_ = list(from_model.state_dict().keys() ) lowerCamelCase_ = list(our_model.state_dict().keys() ) print(len(__UpperCamelCase ) ,len(__UpperCamelCase ) ) for i in range(len(__UpperCamelCase ) ): lowerCamelCase_ = weights[og_keys[i]] our_model.load_state_dict(__UpperCamelCase ) lowerCamelCase_ = torch.randn((2, 3, 2_24, 2_24) ) lowerCamelCase_ = from_model(__UpperCamelCase ) lowerCamelCase_ = our_model(__UpperCamelCase ).logits assert torch.allclose(__UpperCamelCase ,__UpperCamelCase ), "The model logits don't match the original one." lowerCamelCase_ = name print(__UpperCamelCase ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) lowerCamelCase_ = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(f'''Pushed {checkpoint_name}''' ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = None ,__UpperCamelCase = True ) -> Optional[Any]: lowerCamelCase_ = 'imagenet-1k-id2label.json' lowerCamelCase_ = 10_00 lowerCamelCase_ = (1, num_labels) lowerCamelCase_ = 'huggingface/label-files' lowerCamelCase_ = num_labels lowerCamelCase_ = json.load(open(hf_hub_download(__UpperCamelCase ,__UpperCamelCase ,repo_type='dataset' ) ,'r' ) ) lowerCamelCase_ = {int(__UpperCamelCase ): v for k, v in idalabel.items()} lowerCamelCase_ = idalabel lowerCamelCase_ = {v: k for k, v in idalabel.items()} lowerCamelCase_ = partial(__UpperCamelCase ,num_labels=__UpperCamelCase ,idalabel=__UpperCamelCase ,labelaid=__UpperCamelCase ) lowerCamelCase_ = { 'levit-128S': 1_28, 'levit-128': 1_28, 'levit-192': 1_92, 'levit-256': 2_56, 'levit-384': 3_84, } lowerCamelCase_ = { 'levit-128S': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] ,num_attention_heads=[4, 6, 8] ,depths=[2, 3, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,), 'levit-128': ImageNetPreTrainedConfig( hidden_sizes=[1_28, 2_56, 3_84] ,num_attention_heads=[4, 8, 12] ,depths=[4, 4, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,), 'levit-192': ImageNetPreTrainedConfig( hidden_sizes=[1_92, 2_88, 3_84] ,num_attention_heads=[3, 5, 6] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,), 'levit-256': ImageNetPreTrainedConfig( hidden_sizes=[2_56, 3_84, 5_12] ,num_attention_heads=[4, 6, 8] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,), 'levit-384': ImageNetPreTrainedConfig( hidden_sizes=[3_84, 5_12, 7_68] ,num_attention_heads=[6, 9, 12] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0.1 ,), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] ,__UpperCamelCase ,names_to_config[model_name] ,__UpperCamelCase ,__UpperCamelCase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) return config, expected_shape if __name__ == "__main__": A_ = 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 Levit* architecture,", ) parser.add_argument( "--pytorch_dump_folder_path", default="levit-dump-folder/", type=Path, required=False, help="Path to the output PyTorch model directory.", ) parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub") parser.add_argument( "--no-push_to_hub", dest="push_to_hub", action="store_false", help="Do not push model and image processor to the hub", ) A_ = parser.parse_args() A_ = 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)
42
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} A_ = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } A_ = { "allenai/longformer-base-4096": 4_096, "allenai/longformer-large-4096": 4_096, "allenai/longformer-large-4096-finetuned-triviaqa": 4_096, "allenai/longformer-base-4096-extra.pos.embd.only": 4_096, "allenai/longformer-large-4096-extra.pos.embd.only": 4_096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _UpperCamelCase ( ) -> Any: lowerCamelCase_ = ( list(range(ord('!' ) ,ord('~' ) + 1 ) ) + list(range(ord('¡' ) ,ord('¬' ) + 1 ) ) + list(range(ord('®' ) ,ord('ÿ' ) + 1 ) ) ) lowerCamelCase_ = bs[:] lowerCamelCase_ = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 lowerCamelCase_ = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase ,__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: lowerCamelCase_ = set() lowerCamelCase_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCamelCase_ = char return pairs class UpperCAmelCase ( UpperCAmelCase__ ): '''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 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="replace" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else bos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else eos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else sep_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else cls_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else unk_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( errors=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as vocab_handle: lowerCamelCase_ = json.load(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {v: k for k, v in self.encoder.items()} lowerCamelCase_ = errors # how to handle errors in decoding lowerCamelCase_ = bytes_to_unicode() lowerCamelCase_ = {v: k for k, v in self.byte_encoder.items()} with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as merges_handle: lowerCamelCase_ = merges_handle.read().split('\n' )[1:-1] lowerCamelCase_ = [tuple(merge.split() ) for merge in bpe_merges] lowerCamelCase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowerCamelCase_ = {} lowerCamelCase_ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowerCamelCase_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' return len(self.encoder ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' if token in self.cache: return self.cache[token] lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) if not pairs: return token while True: lowerCamelCase_ = min(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break lowerCamelCase_ ,lowerCamelCase_ = bigram lowerCamelCase_ = [] lowerCamelCase_ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): try: lowerCamelCase_ = word.index(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCamelCase_ = j if word[i] == first and i < len(SCREAMING_SNAKE_CASE_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = new_word if len(SCREAMING_SNAKE_CASE_ ) == 1: break else: lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = ' '.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = word return word def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' lowerCamelCase_ = [] for token in re.findall(self.pat , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(SCREAMING_SNAKE_CASE_ ).split(' ' ) ) return bpe_tokens def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' return self.encoder.get(SCREAMING_SNAKE_CASE_ , self.encoder.get(self.unk_token ) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' return self.decoder.get(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = ''.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) + '\n' ) lowerCamelCase_ = 0 with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ' Please check that the tokenizer is not corrupted!' ) lowerCamelCase_ = token_index writer.write(' '.join(SCREAMING_SNAKE_CASE_ ) + '\n' ) index += 1 return vocab_file, merge_file def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] lowerCamelCase_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' lowerCamelCase_ = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(SCREAMING_SNAKE_CASE_ ) > 0 and not text[0].isspace()): lowerCamelCase_ = ' ' + text return (text, kwargs)
42
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A_ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["GPTSw3Tokenizer"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
42
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} A_ = { "vocab_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt" ), "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt", "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt", "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt", "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt", }, "tokenizer_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json" ), "google/realm-orqa-nq-openqa": ( "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-nq-reader": ( "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-openqa": ( "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-reader": ( "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json" ), }, } A_ = { "google/realm-cc-news-pretrained-embedder": 512, "google/realm-cc-news-pretrained-encoder": 512, "google/realm-cc-news-pretrained-scorer": 512, "google/realm-cc-news-pretrained-openqa": 512, "google/realm-orqa-nq-openqa": 512, "google/realm-orqa-nq-reader": 512, "google/realm-orqa-wq-openqa": 512, "google/realm-orqa-wq-reader": 512, } A_ = { "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-reader": {"do_lower_case": True}, "google/realm-orqa-wq-openqa": {"do_lower_case": True}, "google/realm-orqa-wq-reader": {"do_lower_case": True}, } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ = RealmTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="[UNK]" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="[PAD]" , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[MASK]" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> List[Any]: '''simple docstring''' super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , do_lower_case=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , SCREAMING_SNAKE_CASE_ ) != do_lower_case or normalizer_state.get('strip_accents' , SCREAMING_SNAKE_CASE_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , SCREAMING_SNAKE_CASE_ ) != tokenize_chinese_chars ): lowerCamelCase_ = getattr(SCREAMING_SNAKE_CASE_ , normalizer_state.pop('type' ) ) lowerCamelCase_ = do_lower_case lowerCamelCase_ = strip_accents lowerCamelCase_ = tokenize_chinese_chars lowerCamelCase_ = normalizer_class(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = do_lower_case def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = PaddingStrategy.MAX_LENGTH lowerCamelCase_ = text lowerCamelCase_ = kwargs.pop('text_pair' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = kwargs.pop('return_tensors' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'input_ids': [], 'attention_mask': [], 'token_type_ids': [], } for idx, candidate_text in enumerate(SCREAMING_SNAKE_CASE_ ): if batch_text_pair is not None: lowerCamelCase_ = batch_text_pair[idx] else: lowerCamelCase_ = None lowerCamelCase_ = super().__call__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = encoded_candidates.get('input_ids' ) lowerCamelCase_ = encoded_candidates.get('attention_mask' ) lowerCamelCase_ = encoded_candidates.get('token_type_ids' ) if encoded_input_ids is not None: output_data["input_ids"].append(SCREAMING_SNAKE_CASE_ ) if encoded_attention_mask is not None: output_data["attention_mask"].append(SCREAMING_SNAKE_CASE_ ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {key: item for key, item in output_data.items() if len(SCREAMING_SNAKE_CASE_ ) != 0} return BatchEncoding(SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' lowerCamelCase_ = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
42
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = KandinskyVaaControlnetImgaImgPipeline SCREAMING_SNAKE_CASE_ = ['image_embeds', 'negative_image_embeds', 'image', 'hint'] SCREAMING_SNAKE_CASE_ = ['image_embeds', 'negative_image_embeds', 'image', 'hint'] SCREAMING_SNAKE_CASE_ = [ 'generator', 'height', 'width', 'strength', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] SCREAMING_SNAKE_CASE_ = False @property def UpperCamelCase( self ) -> Tuple: '''simple docstring''' return 32 @property def UpperCamelCase( self ) -> Dict: '''simple docstring''' return 32 @property def UpperCamelCase( self ) -> int: '''simple docstring''' return self.time_input_dim @property def UpperCamelCase( self ) -> str: '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' return 100 @property def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = { 'in_channels': 8, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'image_hint', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } lowerCamelCase_ = UNetaDConditionModel(**SCREAMING_SNAKE_CASE_ ) return model @property def UpperCamelCase( self ) -> Dict: '''simple docstring''' return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def UpperCamelCase( self ) -> str: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = VQModel(**self.dummy_movq_kwargs ) return model def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = self.dummy_unet lowerCamelCase_ = self.dummy_movq lowerCamelCase_ = { 'num_train_timesteps': 1000, 'beta_schedule': 'linear', 'beta_start': 0.00_085, 'beta_end': 0.012, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } lowerCamelCase_ = DDIMScheduler(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( SCREAMING_SNAKE_CASE_ ) # create init_image lowerCamelCase_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert('RGB' ).resize((256, 256) ) # create hint lowerCamelCase_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) if str(SCREAMING_SNAKE_CASE_ ).startswith('mps' ): lowerCamelCase_ = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'image': init_image, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'hint': hint, 'generator': generator, 'height': 64, 'width': 64, 'num_inference_steps': 10, 'guidance_scale': 7.0, 'strength': 0.2, 'output_type': 'np', } return inputs def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = 'cpu' lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase_ = output.images lowerCamelCase_ = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) , return_dict=SCREAMING_SNAKE_CASE_ , )[0] lowerCamelCase_ = image[0, -3:, -3:, -1] lowerCamelCase_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase_ = np.array( [0.54_985_034, 0.55_509_365, 0.52_561_504, 0.5_570_494, 0.5_593_818, 0.5_263_979, 0.50_285_643, 0.5_069_846, 0.51_196_736] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy' ) lowerCamelCase_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) lowerCamelCase_ = init_image.resize((512, 512) ) lowerCamelCase_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/hint_image_cat.png' ) lowerCamelCase_ = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE_ ) ).float() / 255.0 lowerCamelCase_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) lowerCamelCase_ = 'A robot, 4k photo' lowerCamelCase_ = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-controlnet-depth' , torch_dtype=torch.floataa ) lowerCamelCase_ = pipeline.to(SCREAMING_SNAKE_CASE_ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device='cpu' ).manual_seed(0 ) lowerCamelCase_ ,lowerCamelCase_ = pipe_prior( SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , strength=0.85 , generator=SCREAMING_SNAKE_CASE_ , negative_prompt='' , ).to_tuple() lowerCamelCase_ = pipeline( image=SCREAMING_SNAKE_CASE_ , image_embeds=SCREAMING_SNAKE_CASE_ , negative_image_embeds=SCREAMING_SNAKE_CASE_ , hint=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=100 , height=512 , width=512 , strength=0.5 , output_type='np' , ) lowerCamelCase_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
42
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __UpperCamelCase ) -> bool: lowerCamelCase_ = str(__UpperCamelCase ) return len(__UpperCamelCase ) == 9 and set(__UpperCamelCase ) == set('123456789' ) def _UpperCamelCase ( ) -> int | None: for base_num in range(99_99 ,49_99 ,-1 ): lowerCamelCase_ = 10_00_02 * base_num if is_9_pandigital(__UpperCamelCase ): return candidate for base_num in range(3_33 ,99 ,-1 ): lowerCamelCase_ = 1_00_20_03 * base_num if is_9_pandigital(__UpperCamelCase ): return candidate return None if __name__ == "__main__": print(f'''{solution() = }''')
42
1
'''simple docstring''' from ...processing_utils import ProcessorMixin class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['image_processor', 'feature_extractor'] SCREAMING_SNAKE_CASE_ = 'TvltImageProcessor' SCREAMING_SNAKE_CASE_ = 'TvltFeatureExtractor' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' super().__init__(image_processor=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = image_processor lowerCamelCase_ = feature_extractor def __call__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) -> List[str]: '''simple docstring''' if images is None and audio is None: raise ValueError('You need to specify either an `images` or `audio` input to process.' ) lowerCamelCase_ = None if images is not None: lowerCamelCase_ = self.image_processor(SCREAMING_SNAKE_CASE_ , mask_pixel=SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if images_mixed is not None: lowerCamelCase_ = self.image_processor(SCREAMING_SNAKE_CASE_ , is_mixed=SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: lowerCamelCase_ = self.feature_extractor( SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , mask_audio=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {} if audio is not None: output_dict.update(SCREAMING_SNAKE_CASE_ ) if images is not None: output_dict.update(SCREAMING_SNAKE_CASE_ ) if images_mixed_dict is not None: output_dict.update(SCREAMING_SNAKE_CASE_ ) return output_dict @property def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = self.image_processor.model_input_names lowerCamelCase_ = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
42
'''simple docstring''' A_ = "Input must be a string of 8 numbers plus letter" A_ = "TRWAGMYFPDXBNJZSQVHLCKE" def _UpperCamelCase ( __UpperCamelCase ) -> bool: if not isinstance(__UpperCamelCase ,__UpperCamelCase ): lowerCamelCase_ = f'''Expected string as input, found {type(__UpperCamelCase ).__name__}''' raise TypeError(__UpperCamelCase ) lowerCamelCase_ = spanish_id.replace('-' ,'' ).upper() if len(__UpperCamelCase ) != 9: raise ValueError(__UpperCamelCase ) try: lowerCamelCase_ = int(spanish_id_clean[0:8] ) lowerCamelCase_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(__UpperCamelCase ) from ex if letter.isdigit(): raise ValueError(__UpperCamelCase ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
42
1
'''simple docstring''' import logging import os from .state import PartialState class UpperCAmelCase ( logging.LoggerAdapter ): '''simple docstring''' @staticmethod def UpperCamelCase( SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' if PartialState._shared_state == {}: raise RuntimeError( 'You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.' ) lowerCamelCase_ = kwargs.pop('main_process_only' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = kwargs.pop('in_order' , SCREAMING_SNAKE_CASE_ ) if self.isEnabledFor(SCREAMING_SNAKE_CASE_ ): if self._should_log(SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ ,lowerCamelCase_ = self.process(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.logger.log(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) elif in_order: lowerCamelCase_ = PartialState() for i in range(state.num_processes ): if i == state.process_index: lowerCamelCase_ ,lowerCamelCase_ = self.process(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.logger.log(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) state.wait_for_everyone() def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = None ) -> Optional[int]: if log_level is None: lowerCamelCase_ = os.environ.get('ACCELERATE_LOG_LEVEL' ,__UpperCamelCase ) lowerCamelCase_ = logging.getLogger(__UpperCamelCase ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(__UpperCamelCase ,{} )
42
'''simple docstring''' import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = GPTSanJapaneseTokenizer SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = {'do_clean_text': False, 'add_prefix_space': False} def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' super().setUp() # fmt: off lowerCamelCase_ = ['こん', 'こんに', 'にちは', 'ばんは', '世界,㔺界', '、', '。', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on lowerCamelCase_ = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # 😀 lowerCamelCase_ = {'unk_token': '<unk>'} lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、世界。😀' return input_text, output_text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.get_input_output_texts(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ ) return text, ids def UpperCamelCase( self ) -> Tuple: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。 こんばんは、㔺界。' lowerCamelCase_ = ['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。'] lowerCamelCase_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids without special tokens lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids with special tokens lowerCamelCase_ = tokens + [tokenizer.unk_token] lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。' lowerCamelCase_ = 'こんにちは、、、、世界。こんばんは、、、、世界。' lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。こんばんは、世界。😀' lowerCamelCase_ = tokenizer.encode(prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode('' , prefix_text=prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = [1] + [0] * (len_prefix + len_text + 1) lowerCamelCase_ = [1] * (len_prefix + len_text + 1) + [0] lowerCamelCase_ = [1] + [1] * (len_prefix) + [0] * (len_text + 1) lowerCamelCase_ = tokenizer(prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = tokenizer.encode('あンいワ' ) lowerCamelCase_ = tokenizer.encode('' , prefix_text='あンいワ' ) lowerCamelCase_ = tokenizer.encode('いワ' , prefix_text='あン' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = [['武田信玄', 'は、'], ['織田信長', 'の配下の、']] lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) # fmt: off lowerCamelCase_ = [[35993, 8640, 25948, 35998, 30647, 35675, 35999, 35999], [35993, 10382, 9868, 35998, 30646, 9459, 30646, 35675]] lowerCamelCase_ = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] lowerCamelCase_ = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass
42
1
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler A_ = 16 A_ = 32 def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = 16 ,__UpperCamelCase = "bert-base-cased" ) -> List[Any]: lowerCamelCase_ = AutoTokenizer.from_pretrained(__UpperCamelCase ) lowerCamelCase_ = load_dataset('glue' ,'mrpc' ) def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) lowerCamelCase_ = tokenizer(examples['sentence1'] ,examples['sentence2'] ,truncation=__UpperCamelCase ,max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowerCamelCase_ = datasets.map( __UpperCamelCase ,batched=__UpperCamelCase ,remove_columns=['idx', 'sentence1', 'sentence2'] ,load_from_cache_file=__UpperCamelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCamelCase_ = tokenized_datasets.rename_column('label' ,'labels' ) 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. lowerCamelCase_ = DataLoader( tokenized_datasets['train'] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) lowerCamelCase_ = DataLoader( tokenized_datasets['validation'] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Union[str, Any]: model.eval() lowerCamelCase_ = 0 for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times lowerCamelCase_ ,lowerCamelCase_ = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__UpperCamelCase ) - 1: lowerCamelCase_ = predictions[: len(eval_dataloader.dataset ) - samples_seen] lowerCamelCase_ = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__UpperCamelCase ,references=__UpperCamelCase ,) lowerCamelCase_ = metric.compute() return eval_metric["accuracy"] def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> List[str]: # Initialize accelerator lowerCamelCase_ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCamelCase_ = config['lr'] lowerCamelCase_ = int(config['num_epochs'] ) lowerCamelCase_ = int(config['seed'] ) lowerCamelCase_ = int(config['batch_size'] ) lowerCamelCase_ = args.model_name_or_path set_seed(__UpperCamelCase ) lowerCamelCase_ ,lowerCamelCase_ = get_dataloaders(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCamelCase_ = AutoModelForSequenceClassification.from_pretrained(__UpperCamelCase ,return_dict=__UpperCamelCase ) # Instantiate optimizer lowerCamelCase_ = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowerCamelCase_ = optimizer_cls(params=model.parameters() ,lr=__UpperCamelCase ) if accelerator.state.deepspeed_plugin is not None: lowerCamelCase_ = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: lowerCamelCase_ = 1 lowerCamelCase_ = (len(__UpperCamelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowerCamelCase_ = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase ,num_warmup_steps=0 ,num_training_steps=__UpperCamelCase ,) else: lowerCamelCase_ = DummyScheduler(__UpperCamelCase ,total_num_steps=__UpperCamelCase ,warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = accelerator.prepare( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # We need to keep track of how many total steps we have iterated over lowerCamelCase_ = 0 # We also need to keep track of the stating epoch so files are named properly lowerCamelCase_ = 0 lowerCamelCase_ = evaluate.load('glue' ,'mrpc' ) lowerCamelCase_ = num_epochs if args.partial_train_epoch is not None: lowerCamelCase_ = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) lowerCamelCase_ = args.resume_from_checkpoint.split('epoch_' )[1] lowerCamelCase_ = '' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break lowerCamelCase_ = int(__UpperCamelCase ) + 1 lowerCamelCase_ = evaluation_loop(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) accelerator.print('resumed checkpoint performance:' ,__UpperCamelCase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:' ,lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:' ,optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir ,f'''state_{starting_epoch-1}.json''' ) ,'r' ) as f: lowerCamelCase_ = json.load(__UpperCamelCase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model lowerCamelCase_ = {} for epoch in range(__UpperCamelCase ,__UpperCamelCase ): model.train() for step, batch in enumerate(__UpperCamelCase ): lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.loss lowerCamelCase_ = loss / gradient_accumulation_steps accelerator.backward(__UpperCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 lowerCamelCase_ = f'''epoch_{epoch}''' lowerCamelCase_ = os.path.join(args.output_dir ,__UpperCamelCase ) accelerator.save_state(__UpperCamelCase ) lowerCamelCase_ = evaluation_loop(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) lowerCamelCase_ = accuracy lowerCamelCase_ = lr_scheduler.get_lr()[0] lowerCamelCase_ = optimizer.param_groups[0]['lr'] lowerCamelCase_ = epoch lowerCamelCase_ = overall_step accelerator.print(f'''epoch {epoch}:''' ,__UpperCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,f'''state_{epoch}.json''' ) ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( ) -> str: lowerCamelCase_ = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' ,type=__UpperCamelCase ,default='bert-base-cased' ,help='Path to pretrained model or model identifier from huggingface.co/models.' ,required=__UpperCamelCase ,) parser.add_argument( '--output_dir' ,type=__UpperCamelCase ,default='.' ,help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' ,) parser.add_argument( '--resume_from_checkpoint' ,type=__UpperCamelCase ,default=__UpperCamelCase ,help='If the training should continue from a checkpoint folder.' ,) parser.add_argument( '--partial_train_epoch' ,type=__UpperCamelCase ,default=__UpperCamelCase ,help='If passed, the training will stop after this number of epochs.' ,) parser.add_argument( '--num_epochs' ,type=__UpperCamelCase ,default=2 ,help='Number of train epochs.' ,) lowerCamelCase_ = parser.parse_args() lowerCamelCase_ = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(__UpperCamelCase ,__UpperCamelCase ) if __name__ == "__main__": main()
42
'''simple docstring''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Dict: '''simple docstring''' super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> List[str]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory lowerCamelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> List[str]: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}''' ) 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 (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(SCREAMING_SNAKE_CASE_ )}.''' ) # get prompt text embeddings lowerCamelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=self.tokenizer.model_max_length , return_tensors='pt' , ) lowerCamelCase_ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowerCamelCase_ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( 'The following part of your input was truncated because CLIP can only handle sequences up to' f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) lowerCamelCase_ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: lowerCamelCase_ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = text_embeddings.shape lowerCamelCase_ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) lowerCamelCase_ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # 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. lowerCamelCase_ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: lowerCamelCase_ = 42 if negative_prompt is None: lowerCamelCase_ = [''] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( f'''`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=''' f''' {type(SCREAMING_SNAKE_CASE_ )}.''' ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( f'''`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:''' f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' ' the batch size of `prompt`.' ) else: lowerCamelCase_ = negative_prompt lowerCamelCase_ = text_input_ids.shape[-1] lowerCamelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='pt' , ) lowerCamelCase_ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCamelCase_ = uncond_embeddings.shape[1] lowerCamelCase_ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) lowerCamelCase_ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCamelCase_ = 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`. lowerCamelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) lowerCamelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) lowerCamelCase_ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps lowerCamelCase_ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='cpu' , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) lowerCamelCase_ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='cpu' , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: lowerCamelCase_ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) lowerCamelCase_ = latents_reference.to(self.device ) lowerCamelCase_ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images lowerCamelCase_ = (latents_shape[3] - latents_shape_reference[3]) // 2 lowerCamelCase_ = (latents_shape[2] - latents_shape_reference[2]) // 2 lowerCamelCase_ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx lowerCamelCase_ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy lowerCamelCase_ = 0 if dx < 0 else dx lowerCamelCase_ = 0 if dy < 0 else dy lowerCamelCase_ = max(-dx , 0 ) lowerCamelCase_ = max(-dy , 0 ) # import pdb # pdb.set_trace() lowerCamelCase_ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand lowerCamelCase_ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ = 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] lowerCamelCase_ = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ = {} if accepts_eta: lowerCamelCase_ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance lowerCamelCase_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCamelCase_ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual lowerCamelCase_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: lowerCamelCase_ ,lowerCamelCase_ = noise_pred.chunk(2 ) lowerCamelCase_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 1 / 0.18_215 * latents lowerCamelCase_ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample lowerCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: lowerCamelCase_ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors='pt' ).to( self.device ) lowerCamelCase_ ,lowerCamelCase_ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: lowerCamelCase_ = None if output_type == "pil": lowerCamelCase_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
42
1
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class UpperCAmelCase ( datasets.BuilderConfig ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = None class UpperCAmelCase ( datasets.ArrowBasedBuilder ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = PandasConfig def UpperCamelCase( self ) -> str: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) lowerCamelCase_ = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE_ , (str, list, tuple) ): lowerCamelCase_ = data_files if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCamelCase_ = [dl_manager.iter_files(SCREAMING_SNAKE_CASE_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] lowerCamelCase_ = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCamelCase_ = [dl_manager.iter_files(SCREAMING_SNAKE_CASE_ ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE_ , gen_kwargs={'files': files} ) ) return splits def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> pa.Table: '''simple docstring''' if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example lowerCamelCase_ = table_cast(SCREAMING_SNAKE_CASE_ , self.config.features.arrow_schema ) return pa_table def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' for i, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE_ ) ): with open(SCREAMING_SNAKE_CASE_ , 'rb' ) as f: lowerCamelCase_ = pa.Table.from_pandas(pd.read_pickle(SCREAMING_SNAKE_CASE_ ) ) yield i, self._cast_table(SCREAMING_SNAKE_CASE_ )
42
'''simple docstring''' import pprint import requests A_ = "https://zenquotes.io/api" def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/today' ).json() def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": A_ = random_quotes() pprint.pprint(response)
42
1
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json" ), } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'xlm-prophetnet' SCREAMING_SNAKE_CASE_ = ['past_key_values'] SCREAMING_SNAKE_CASE_ = { 'num_attention_heads': 'num_encoder_attention_heads', } def __init__( self , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = "gelu" , SCREAMING_SNAKE_CASE_ = 30522 , SCREAMING_SNAKE_CASE_ = 1024 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 2 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 128 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 2 , **SCREAMING_SNAKE_CASE_ , ) -> Tuple: '''simple docstring''' lowerCamelCase_ = vocab_size lowerCamelCase_ = hidden_size lowerCamelCase_ = encoder_ffn_dim lowerCamelCase_ = num_encoder_layers lowerCamelCase_ = num_encoder_attention_heads lowerCamelCase_ = decoder_ffn_dim lowerCamelCase_ = num_decoder_layers lowerCamelCase_ = num_decoder_attention_heads lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = init_std # Normal(0, this parameter) lowerCamelCase_ = activation_function # parameters for xlmprophetnet lowerCamelCase_ = ngram lowerCamelCase_ = num_buckets lowerCamelCase_ = relative_max_distance lowerCamelCase_ = disable_ngram_loss lowerCamelCase_ = eps # 3 Types of Dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = dropout lowerCamelCase_ = use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , add_cross_attention=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @property def UpperCamelCase( self ) -> int: '''simple docstring''' return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' raise NotImplementedError( 'This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and' ' `num_decoder_layers`.' )
42
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=33 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ) -> int: '''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_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = num_attention_heads lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = type_vocab_size lowerCamelCase_ = type_sequence_label_size lowerCamelCase_ = initializer_range lowerCamelCase_ = num_labels lowerCamelCase_ = num_choices lowerCamelCase_ = scope def UpperCamelCase( self ) -> str: '''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 lowerCamelCase_ = None lowerCamelCase_ = None if self.use_labels: lowerCamelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase_ = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase_ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase( self ) -> List[str]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = EsmModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = EsmForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' lowerCamelCase_ = self.num_labels lowerCamelCase_ = EsmForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) = config_and_inputs lowerCamelCase_ = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ = () SCREAMING_SNAKE_CASE_ = ( { 'feature-extraction': EsmModel, 'fill-mask': EsmForMaskedLM, 'text-classification': EsmForSequenceClassification, 'token-classification': EsmForTokenClassification, 'zero-shot': EsmForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = EsmModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> str: '''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(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ = EsmModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()[0] lowerCamelCase_ = EsmEmbeddings(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) lowerCamelCase_ = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) lowerCamelCase_ = create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE_ , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()[0] lowerCamelCase_ = EsmEmbeddings(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.empty(2 , 4 , 30 ) lowerCamelCase_ = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] lowerCamelCase_ = torch.as_tensor([expected_single_positions, expected_single_positions] ) lowerCamelCase_ = embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE_ ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) @unittest.skip('Esm does not support embedding resizing' ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' pass @unittest.skip('Esm does not support embedding resizing' ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass @require_torch class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' with torch.no_grad(): lowerCamelCase_ = EsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() lowerCamelCase_ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )[0] lowerCamelCase_ = 33 lowerCamelCase_ = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCamelCase( self ) -> Tuple: '''simple docstring''' with torch.no_grad(): lowerCamelCase_ = EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() lowerCamelCase_ = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )[0] # compare the actual values for a slice. lowerCamelCase_ = torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
42
1
'''simple docstring''' import math from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "facebook/data2vec-base-960h": "https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json", # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'data2vec-audio' def __init__( self , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1E-5 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=(512, 512, 512, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE_=(5, 2, 2, 2, 2, 2, 2) , SCREAMING_SNAKE_CASE_=(10, 3, 3, 3, 3, 2, 2) , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=19 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=0.05 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_="sum" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=(512, 512, 512, 512, 1500) , SCREAMING_SNAKE_CASE_=(5, 3, 3, 1, 1) , SCREAMING_SNAKE_CASE_=(1, 2, 3, 1, 1) , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> List[Any]: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = hidden_size lowerCamelCase_ = feat_extract_activation lowerCamelCase_ = list(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = list(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = list(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = conv_bias lowerCamelCase_ = num_conv_pos_embeddings lowerCamelCase_ = num_conv_pos_embedding_groups lowerCamelCase_ = conv_pos_kernel_size lowerCamelCase_ = len(self.conv_dim ) lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = num_attention_heads lowerCamelCase_ = hidden_dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = feat_proj_dropout lowerCamelCase_ = final_dropout lowerCamelCase_ = layerdrop lowerCamelCase_ = layer_norm_eps lowerCamelCase_ = initializer_range lowerCamelCase_ = vocab_size lowerCamelCase_ = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowerCamelCase_ = mask_time_prob lowerCamelCase_ = mask_time_length lowerCamelCase_ = mask_time_min_masks lowerCamelCase_ = mask_feature_prob lowerCamelCase_ = mask_feature_length lowerCamelCase_ = mask_feature_min_masks # ctc loss lowerCamelCase_ = ctc_loss_reduction lowerCamelCase_ = ctc_zero_infinity # adapter lowerCamelCase_ = add_adapter lowerCamelCase_ = adapter_kernel_size lowerCamelCase_ = adapter_stride lowerCamelCase_ = num_adapter_layers lowerCamelCase_ = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. lowerCamelCase_ = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. lowerCamelCase_ = list(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = list(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = list(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = xvector_output_dim @property def UpperCamelCase( self ) -> Dict: '''simple docstring''' return math.prod(self.conv_stride )
42
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A_ = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
42
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "vinvino02/glpn-kitti": "https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json", # See all GLPN models at https://huggingface.co/models?filter=glpn } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'glpn' def __init__( self , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[8, 4, 2, 1] , SCREAMING_SNAKE_CASE_=[32, 64, 160, 256] , SCREAMING_SNAKE_CASE_=[7, 3, 3, 3] , SCREAMING_SNAKE_CASE_=[4, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[1, 2, 5, 8] , SCREAMING_SNAKE_CASE_=[4, 4, 4, 4] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=1E-6 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=-1 , **SCREAMING_SNAKE_CASE_ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = num_channels lowerCamelCase_ = num_encoder_blocks lowerCamelCase_ = depths lowerCamelCase_ = sr_ratios lowerCamelCase_ = hidden_sizes lowerCamelCase_ = patch_sizes lowerCamelCase_ = strides lowerCamelCase_ = mlp_ratios lowerCamelCase_ = num_attention_heads lowerCamelCase_ = hidden_act lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = initializer_range lowerCamelCase_ = drop_path_rate lowerCamelCase_ = layer_norm_eps lowerCamelCase_ = decoder_hidden_size lowerCamelCase_ = max_depth lowerCamelCase_ = head_in_index
42
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json" ), } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'xlm-prophetnet' SCREAMING_SNAKE_CASE_ = ['past_key_values'] SCREAMING_SNAKE_CASE_ = { 'num_attention_heads': 'num_encoder_attention_heads', } def __init__( self , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = "gelu" , SCREAMING_SNAKE_CASE_ = 30522 , SCREAMING_SNAKE_CASE_ = 1024 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 2 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 128 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 2 , **SCREAMING_SNAKE_CASE_ , ) -> Tuple: '''simple docstring''' lowerCamelCase_ = vocab_size lowerCamelCase_ = hidden_size lowerCamelCase_ = encoder_ffn_dim lowerCamelCase_ = num_encoder_layers lowerCamelCase_ = num_encoder_attention_heads lowerCamelCase_ = decoder_ffn_dim lowerCamelCase_ = num_decoder_layers lowerCamelCase_ = num_decoder_attention_heads lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = init_std # Normal(0, this parameter) lowerCamelCase_ = activation_function # parameters for xlmprophetnet lowerCamelCase_ = ngram lowerCamelCase_ = num_buckets lowerCamelCase_ = relative_max_distance lowerCamelCase_ = disable_ngram_loss lowerCamelCase_ = eps # 3 Types of Dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = dropout lowerCamelCase_ = use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , add_cross_attention=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @property def UpperCamelCase( self ) -> int: '''simple docstring''' return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' raise NotImplementedError( 'This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and' ' `num_decoder_layers`.' )
42
1
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> int: assert isinstance(__UpperCamelCase ,__UpperCamelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' ,[False, True] ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> List[str]: lowerCamelCase_ = tmp_path / 'cache' lowerCamelCase_ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase_ = JsonDatasetReader(__UpperCamelCase ,cache_dir=__UpperCamelCase ,keep_in_memory=__UpperCamelCase ).read() _check_json_dataset(__UpperCamelCase ,__UpperCamelCase ) @pytest.mark.parametrize( 'features' ,[ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] ,) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Dict: lowerCamelCase_ = tmp_path / 'cache' lowerCamelCase_ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} lowerCamelCase_ = features.copy() if features else default_expected_features lowerCamelCase_ = ( Features({feature: Value(__UpperCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase_ = JsonDatasetReader(__UpperCamelCase ,features=__UpperCamelCase ,cache_dir=__UpperCamelCase ).read() _check_json_dataset(__UpperCamelCase ,__UpperCamelCase ) @pytest.mark.parametrize( 'features' ,[ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ] ,) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Optional[int]: lowerCamelCase_ = tmp_path / 'cache' lowerCamelCase_ = {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} lowerCamelCase_ = features.copy() if features else default_expected_features lowerCamelCase_ = ( Features({feature: Value(__UpperCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase_ = JsonDatasetReader(__UpperCamelCase ,features=__UpperCamelCase ,cache_dir=__UpperCamelCase ).read() assert isinstance(__UpperCamelCase ,__UpperCamelCase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} lowerCamelCase_ = {'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} lowerCamelCase_ = features.copy() lowerCamelCase_ = ( Features({feature: Value(__UpperCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase_ = tmp_path / 'cache' lowerCamelCase_ = JsonDatasetReader(__UpperCamelCase ,features=__UpperCamelCase ,cache_dir=__UpperCamelCase ).read() assert isinstance(__UpperCamelCase ,__UpperCamelCase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split' ,[None, NamedSplit('train' ), 'train', 'test'] ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> List[Any]: lowerCamelCase_ = tmp_path / 'cache' lowerCamelCase_ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} lowerCamelCase_ = JsonDatasetReader(__UpperCamelCase ,cache_dir=__UpperCamelCase ,split=__UpperCamelCase ).read() _check_json_dataset(__UpperCamelCase ,__UpperCamelCase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' ,[str, list] ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Optional[Any]: if issubclass(__UpperCamelCase ,__UpperCamelCase ): lowerCamelCase_ = jsonl_path elif issubclass(__UpperCamelCase ,__UpperCamelCase ): lowerCamelCase_ = [jsonl_path] lowerCamelCase_ = tmp_path / 'cache' lowerCamelCase_ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} lowerCamelCase_ = JsonDatasetReader(__UpperCamelCase ,cache_dir=__UpperCamelCase ).read() _check_json_dataset(__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=("train",) ) -> Optional[int]: assert isinstance(__UpperCamelCase ,__UpperCamelCase ) for split in splits: lowerCamelCase_ = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' ,[False, True] ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Dict: lowerCamelCase_ = tmp_path / 'cache' lowerCamelCase_ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase_ = JsonDatasetReader({'train': jsonl_path} ,cache_dir=__UpperCamelCase ,keep_in_memory=__UpperCamelCase ).read() _check_json_datasetdict(__UpperCamelCase ,__UpperCamelCase ) @pytest.mark.parametrize( 'features' ,[ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] ,) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Any: lowerCamelCase_ = tmp_path / 'cache' lowerCamelCase_ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} lowerCamelCase_ = features.copy() if features else default_expected_features lowerCamelCase_ = ( Features({feature: Value(__UpperCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase_ = JsonDatasetReader({'train': jsonl_path} ,features=__UpperCamelCase ,cache_dir=__UpperCamelCase ).read() _check_json_datasetdict(__UpperCamelCase ,__UpperCamelCase ) @pytest.mark.parametrize('split' ,[None, NamedSplit('train' ), 'train', 'test'] ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Any: if split: lowerCamelCase_ = {split: jsonl_path} else: lowerCamelCase_ = 'train' lowerCamelCase_ = {'train': jsonl_path, 'test': jsonl_path} lowerCamelCase_ = tmp_path / 'cache' lowerCamelCase_ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} lowerCamelCase_ = JsonDatasetReader(__UpperCamelCase ,cache_dir=__UpperCamelCase ).read() _check_json_datasetdict(__UpperCamelCase ,__UpperCamelCase ,splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def _UpperCamelCase ( __UpperCamelCase ) -> Union[str, Any]: return json.load(__UpperCamelCase ) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: return [json.loads(__UpperCamelCase ) for line in buffer] class UpperCAmelCase : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , lines=SCREAMING_SNAKE_CASE_ ).write() buffer.seek(0 ) lowerCamelCase_ = load_json_function(SCREAMING_SNAKE_CASE_ ) assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE_ ) assert len(SCREAMING_SNAKE_CASE_ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , lines=SCREAMING_SNAKE_CASE_ , orient=SCREAMING_SNAKE_CASE_ ).write() buffer.seek(0 ) lowerCamelCase_ = load_json(SCREAMING_SNAKE_CASE_ ) assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE_ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE_ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , lines=SCREAMING_SNAKE_CASE_ , num_proc=2 ).write() buffer.seek(0 ) lowerCamelCase_ = load_json_function(SCREAMING_SNAKE_CASE_ ) assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE_ ) assert len(SCREAMING_SNAKE_CASE_ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , lines=SCREAMING_SNAKE_CASE_ , orient=SCREAMING_SNAKE_CASE_ , num_proc=2 ).write() buffer.seek(0 ) lowerCamelCase_ = load_json(SCREAMING_SNAKE_CASE_ ) assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE_ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE_ ) == 10 def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' with pytest.raises(SCREAMING_SNAKE_CASE_ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = tmp_path_factory.mktemp('data' ) / f'''test.json.{extension}''' lowerCamelCase_ = str(shared_datadir / f'''test_file.json.{extension}''' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , compression=SCREAMING_SNAKE_CASE_ ).write() with fsspec.open(SCREAMING_SNAKE_CASE_ , 'rb' , compression='infer' ) as f: lowerCamelCase_ = f.read() with fsspec.open(SCREAMING_SNAKE_CASE_ , 'rb' , compression='infer' ) as f: lowerCamelCase_ = f.read() assert exported_content == original_content
42
'''simple docstring''' import colorsys from PIL import Image # type: ignore def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> float: lowerCamelCase_ = x lowerCamelCase_ = y for step in range(__UpperCamelCase ): # noqa: B007 lowerCamelCase_ = a * a - b * b + x lowerCamelCase_ = 2 * a * b + y lowerCamelCase_ = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _UpperCamelCase ( __UpperCamelCase ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _UpperCamelCase ( __UpperCamelCase ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(__UpperCamelCase ,1 ,1 ) ) def _UpperCamelCase ( __UpperCamelCase = 8_00 ,__UpperCamelCase = 6_00 ,__UpperCamelCase = -0.6 ,__UpperCamelCase = 0 ,__UpperCamelCase = 3.2 ,__UpperCamelCase = 50 ,__UpperCamelCase = True ,) -> Image.Image: lowerCamelCase_ = Image.new('RGB' ,(image_width, image_height) ) lowerCamelCase_ = img.load() # loop through the image-coordinates for image_x in range(__UpperCamelCase ): for image_y in range(__UpperCamelCase ): # determine the figure-coordinates based on the image-coordinates lowerCamelCase_ = figure_width / image_width * image_height lowerCamelCase_ = figure_center_x + (image_x / image_width - 0.5) * figure_width lowerCamelCase_ = figure_center_y + (image_y / image_height - 0.5) * figure_height lowerCamelCase_ = get_distance(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: lowerCamelCase_ = get_color_coded_rgb(__UpperCamelCase ) else: lowerCamelCase_ = get_black_and_white_rgb(__UpperCamelCase ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure A_ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
42
1
'''simple docstring''' import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Tuple: # Construct model if openai_config_file == "": lowerCamelCase_ = OpenAIGPTConfig() else: lowerCamelCase_ = OpenAIGPTConfig.from_json_file(__UpperCamelCase ) lowerCamelCase_ = OpenAIGPTModel(__UpperCamelCase ) # Load weights from numpy load_tf_weights_in_openai_gpt(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # Save pytorch-model lowerCamelCase_ = pytorch_dump_folder_path + '/' + WEIGHTS_NAME lowerCamelCase_ = pytorch_dump_folder_path + '/' + CONFIG_NAME print(f'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(model.state_dict() ,__UpperCamelCase ) print(f'''Save configuration file to {pytorch_config_dump_path}''' ) with open(__UpperCamelCase ,'w' ,encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--openai_checkpoint_folder_path", default=None, type=str, required=True, help="Path to the TensorFlow 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( "--openai_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained OpenAI model. \n" "This specifies the model architecture." ), ) A_ = parser.parse_args() convert_openai_checkpoint_to_pytorch( args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path )
42
'''simple docstring''' from math import isclose, sqrt def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> tuple[float, float, float]: lowerCamelCase_ = point_y / 4 / point_x lowerCamelCase_ = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) lowerCamelCase_ = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) lowerCamelCase_ = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 lowerCamelCase_ = outgoing_gradient**2 + 4 lowerCamelCase_ = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) lowerCamelCase_ = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 lowerCamelCase_ = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) lowerCamelCase_ = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point lowerCamelCase_ = x_minus if isclose(__UpperCamelCase ,__UpperCamelCase ) else x_plus lowerCamelCase_ = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _UpperCamelCase ( __UpperCamelCase = 1.4 ,__UpperCamelCase = -9.6 ) -> int: lowerCamelCase_ = 0 lowerCamelCase_ = first_x_coord lowerCamelCase_ = first_y_coord lowerCamelCase_ = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = next_point(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
42
1
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES A_ = logging.get_logger(__name__) A_ = OrderedDict( [ # Base model mapping ("albert", "FlaxAlbertModel"), ("bart", "FlaxBartModel"), ("beit", "FlaxBeitModel"), ("bert", "FlaxBertModel"), ("big_bird", "FlaxBigBirdModel"), ("blenderbot", "FlaxBlenderbotModel"), ("blenderbot-small", "FlaxBlenderbotSmallModel"), ("clip", "FlaxCLIPModel"), ("distilbert", "FlaxDistilBertModel"), ("electra", "FlaxElectraModel"), ("gpt-sw3", "FlaxGPT2Model"), ("gpt2", "FlaxGPT2Model"), ("gpt_neo", "FlaxGPTNeoModel"), ("gptj", "FlaxGPTJModel"), ("longt5", "FlaxLongT5Model"), ("marian", "FlaxMarianModel"), ("mbart", "FlaxMBartModel"), ("mt5", "FlaxMT5Model"), ("opt", "FlaxOPTModel"), ("pegasus", "FlaxPegasusModel"), ("regnet", "FlaxRegNetModel"), ("resnet", "FlaxResNetModel"), ("roberta", "FlaxRobertaModel"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"), ("roformer", "FlaxRoFormerModel"), ("t5", "FlaxT5Model"), ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"), ("vit", "FlaxViTModel"), ("wav2vec2", "FlaxWav2Vec2Model"), ("whisper", "FlaxWhisperModel"), ("xglm", "FlaxXGLMModel"), ("xlm-roberta", "FlaxXLMRobertaModel"), ] ) A_ = OrderedDict( [ # Model for pre-training mapping ("albert", "FlaxAlbertForPreTraining"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForPreTraining"), ("big_bird", "FlaxBigBirdForPreTraining"), ("electra", "FlaxElectraForPreTraining"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("t5", "FlaxT5ForConditionalGeneration"), ("wav2vec2", "FlaxWav2Vec2ForPreTraining"), ("whisper", "FlaxWhisperForConditionalGeneration"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) A_ = OrderedDict( [ # Model for Masked LM mapping ("albert", "FlaxAlbertForMaskedLM"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForMaskedLM"), ("big_bird", "FlaxBigBirdForMaskedLM"), ("distilbert", "FlaxDistilBertForMaskedLM"), ("electra", "FlaxElectraForMaskedLM"), ("mbart", "FlaxMBartForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) A_ = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("bart", "FlaxBartForConditionalGeneration"), ("blenderbot", "FlaxBlenderbotForConditionalGeneration"), ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"), ("encoder-decoder", "FlaxEncoderDecoderModel"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("marian", "FlaxMarianMTModel"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("pegasus", "FlaxPegasusForConditionalGeneration"), ("t5", "FlaxT5ForConditionalGeneration"), ] ) A_ = OrderedDict( [ # Model for Image-classsification ("beit", "FlaxBeitForImageClassification"), ("regnet", "FlaxRegNetForImageClassification"), ("resnet", "FlaxResNetForImageClassification"), ("vit", "FlaxViTForImageClassification"), ] ) A_ = OrderedDict( [ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"), ] ) A_ = OrderedDict( [ # Model for Causal LM mapping ("bart", "FlaxBartForCausalLM"), ("bert", "FlaxBertForCausalLM"), ("big_bird", "FlaxBigBirdForCausalLM"), ("electra", "FlaxElectraForCausalLM"), ("gpt-sw3", "FlaxGPT2LMHeadModel"), ("gpt2", "FlaxGPT2LMHeadModel"), ("gpt_neo", "FlaxGPTNeoForCausalLM"), ("gptj", "FlaxGPTJForCausalLM"), ("opt", "FlaxOPTForCausalLM"), ("roberta", "FlaxRobertaForCausalLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"), ("xglm", "FlaxXGLMForCausalLM"), ("xlm-roberta", "FlaxXLMRobertaForCausalLM"), ] ) A_ = OrderedDict( [ # Model for Sequence Classification mapping ("albert", "FlaxAlbertForSequenceClassification"), ("bart", "FlaxBartForSequenceClassification"), ("bert", "FlaxBertForSequenceClassification"), ("big_bird", "FlaxBigBirdForSequenceClassification"), ("distilbert", "FlaxDistilBertForSequenceClassification"), ("electra", "FlaxElectraForSequenceClassification"), ("mbart", "FlaxMBartForSequenceClassification"), ("roberta", "FlaxRobertaForSequenceClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"), ("roformer", "FlaxRoFormerForSequenceClassification"), ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"), ] ) A_ = OrderedDict( [ # Model for Question Answering mapping ("albert", "FlaxAlbertForQuestionAnswering"), ("bart", "FlaxBartForQuestionAnswering"), ("bert", "FlaxBertForQuestionAnswering"), ("big_bird", "FlaxBigBirdForQuestionAnswering"), ("distilbert", "FlaxDistilBertForQuestionAnswering"), ("electra", "FlaxElectraForQuestionAnswering"), ("mbart", "FlaxMBartForQuestionAnswering"), ("roberta", "FlaxRobertaForQuestionAnswering"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"), ("roformer", "FlaxRoFormerForQuestionAnswering"), ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"), ] ) A_ = OrderedDict( [ # Model for Token Classification mapping ("albert", "FlaxAlbertForTokenClassification"), ("bert", "FlaxBertForTokenClassification"), ("big_bird", "FlaxBigBirdForTokenClassification"), ("distilbert", "FlaxDistilBertForTokenClassification"), ("electra", "FlaxElectraForTokenClassification"), ("roberta", "FlaxRobertaForTokenClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"), ("roformer", "FlaxRoFormerForTokenClassification"), ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"), ] ) A_ = OrderedDict( [ # Model for Multiple Choice mapping ("albert", "FlaxAlbertForMultipleChoice"), ("bert", "FlaxBertForMultipleChoice"), ("big_bird", "FlaxBigBirdForMultipleChoice"), ("distilbert", "FlaxDistilBertForMultipleChoice"), ("electra", "FlaxElectraForMultipleChoice"), ("roberta", "FlaxRobertaForMultipleChoice"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"), ("roformer", "FlaxRoFormerForMultipleChoice"), ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"), ] ) A_ = OrderedDict( [ ("bert", "FlaxBertForNextSentencePrediction"), ] ) A_ = OrderedDict( [ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"), ("whisper", "FlaxWhisperForConditionalGeneration"), ] ) A_ = OrderedDict( [ ("whisper", "FlaxWhisperForAudioClassification"), ] ) A_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) A_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) A_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) A_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) A_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) A_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) A_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) A_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) A_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) A_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) A_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) A_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) A_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) A_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_MAPPING A_ = auto_class_update(FlaxAutoModel) class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_PRETRAINING_MAPPING A_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING A_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_MASKED_LM_MAPPING A_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING A_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING A_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING A_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING A_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING A_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING A_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING A_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING A_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling") class UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING A_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling" )
42
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = False ) -> bool: if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3_31_70_44_06_46_79_88_73_85_96_19_81 and not allow_probable: raise ValueError( 'Warning: upper bound of deterministic test is exceeded. ' 'Pass allow_probable=True to allow probabilistic test. ' 'A return value of True indicates a probable prime.' ) # array bounds provided by analysis lowerCamelCase_ = [ 20_47, 1_37_36_53, 25_32_60_01, 32_15_03_17_51, 2_15_23_02_89_87_47, 3_47_47_49_66_03_83, 3_41_55_00_71_72_83_21, 1, 3_82_51_23_05_65_46_41_30_51, 1, 1, 31_86_65_85_78_34_03_11_51_16_74_61, 3_31_70_44_06_46_79_88_73_85_96_19_81, ] lowerCamelCase_ = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(__UpperCamelCase ,1 ): if n < _p: # then we have our last prime to check lowerCamelCase_ = primes[:idx] break lowerCamelCase_ ,lowerCamelCase_ = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: lowerCamelCase_ = False for r in range(__UpperCamelCase ): lowerCamelCase_ = pow(__UpperCamelCase ,d * 2**r ,__UpperCamelCase ) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): lowerCamelCase_ = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True def _UpperCamelCase ( ) -> None: assert not miller_rabin(5_61 ) assert miller_rabin(5_63 ) # 2047 assert not miller_rabin(83_82_01 ) assert miller_rabin(83_82_07 ) # 1_373_653 assert not miller_rabin(17_31_60_01 ) assert miller_rabin(17_31_60_17 ) # 25_326_001 assert not miller_rabin(30_78_38_66_41 ) assert miller_rabin(30_78_38_66_53 ) # 3_215_031_751 assert not miller_rabin(1_71_30_45_57_48_01 ) assert miller_rabin(1_71_30_45_57_48_19 ) # 2_152_302_898_747 assert not miller_rabin(2_77_97_99_72_83_07 ) assert miller_rabin(2_77_97_99_72_83_27 ) # 3_474_749_660_383 assert not miller_rabin(1_13_85_00_23_90_94_41 ) assert miller_rabin(1_13_85_00_23_90_95_27 ) # 341_550_071_728_321 assert not miller_rabin(1_27_50_41_01_88_48_80_43_51 ) assert miller_rabin(1_27_50_41_01_88_48_80_43_91 ) # 3_825_123_056_546_413_051 assert not miller_rabin(7_96_66_46_44_58_50_77_87_79_18_67 ) assert miller_rabin(7_96_66_46_44_58_50_77_87_79_19_51 ) # 318_665_857_834_031_151_167_461 assert not miller_rabin(55_28_40_67_74_46_64_78_97_66_03_33 ) assert miller_rabin(55_28_40_67_74_46_64_78_97_66_03_59 ) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
42
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A_ = { "configuration_groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGroupViTModel", "TFGroupViTPreTrainedModel", "TFGroupViTTextModel", "TFGroupViTVisionModel", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
42
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler A_ = 16 A_ = 32 def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = 16 ,__UpperCamelCase = "bert-base-cased" ) -> List[Any]: lowerCamelCase_ = AutoTokenizer.from_pretrained(__UpperCamelCase ) lowerCamelCase_ = load_dataset('glue' ,'mrpc' ) def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) lowerCamelCase_ = tokenizer(examples['sentence1'] ,examples['sentence2'] ,truncation=__UpperCamelCase ,max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowerCamelCase_ = datasets.map( __UpperCamelCase ,batched=__UpperCamelCase ,remove_columns=['idx', 'sentence1', 'sentence2'] ,load_from_cache_file=__UpperCamelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCamelCase_ = tokenized_datasets.rename_column('label' ,'labels' ) 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. lowerCamelCase_ = DataLoader( tokenized_datasets['train'] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) lowerCamelCase_ = DataLoader( tokenized_datasets['validation'] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Union[str, Any]: model.eval() lowerCamelCase_ = 0 for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times lowerCamelCase_ ,lowerCamelCase_ = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__UpperCamelCase ) - 1: lowerCamelCase_ = predictions[: len(eval_dataloader.dataset ) - samples_seen] lowerCamelCase_ = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__UpperCamelCase ,references=__UpperCamelCase ,) lowerCamelCase_ = metric.compute() return eval_metric["accuracy"] def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> List[str]: # Initialize accelerator lowerCamelCase_ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCamelCase_ = config['lr'] lowerCamelCase_ = int(config['num_epochs'] ) lowerCamelCase_ = int(config['seed'] ) lowerCamelCase_ = int(config['batch_size'] ) lowerCamelCase_ = args.model_name_or_path set_seed(__UpperCamelCase ) lowerCamelCase_ ,lowerCamelCase_ = get_dataloaders(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCamelCase_ = AutoModelForSequenceClassification.from_pretrained(__UpperCamelCase ,return_dict=__UpperCamelCase ) # Instantiate optimizer lowerCamelCase_ = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowerCamelCase_ = optimizer_cls(params=model.parameters() ,lr=__UpperCamelCase ) if accelerator.state.deepspeed_plugin is not None: lowerCamelCase_ = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: lowerCamelCase_ = 1 lowerCamelCase_ = (len(__UpperCamelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowerCamelCase_ = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase ,num_warmup_steps=0 ,num_training_steps=__UpperCamelCase ,) else: lowerCamelCase_ = DummyScheduler(__UpperCamelCase ,total_num_steps=__UpperCamelCase ,warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = accelerator.prepare( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # We need to keep track of how many total steps we have iterated over lowerCamelCase_ = 0 # We also need to keep track of the stating epoch so files are named properly lowerCamelCase_ = 0 lowerCamelCase_ = evaluate.load('glue' ,'mrpc' ) lowerCamelCase_ = num_epochs if args.partial_train_epoch is not None: lowerCamelCase_ = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) lowerCamelCase_ = args.resume_from_checkpoint.split('epoch_' )[1] lowerCamelCase_ = '' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break lowerCamelCase_ = int(__UpperCamelCase ) + 1 lowerCamelCase_ = evaluation_loop(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) accelerator.print('resumed checkpoint performance:' ,__UpperCamelCase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:' ,lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:' ,optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir ,f'''state_{starting_epoch-1}.json''' ) ,'r' ) as f: lowerCamelCase_ = json.load(__UpperCamelCase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model lowerCamelCase_ = {} for epoch in range(__UpperCamelCase ,__UpperCamelCase ): model.train() for step, batch in enumerate(__UpperCamelCase ): lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.loss lowerCamelCase_ = loss / gradient_accumulation_steps accelerator.backward(__UpperCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 lowerCamelCase_ = f'''epoch_{epoch}''' lowerCamelCase_ = os.path.join(args.output_dir ,__UpperCamelCase ) accelerator.save_state(__UpperCamelCase ) lowerCamelCase_ = evaluation_loop(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) lowerCamelCase_ = accuracy lowerCamelCase_ = lr_scheduler.get_lr()[0] lowerCamelCase_ = optimizer.param_groups[0]['lr'] lowerCamelCase_ = epoch lowerCamelCase_ = overall_step accelerator.print(f'''epoch {epoch}:''' ,__UpperCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,f'''state_{epoch}.json''' ) ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( ) -> str: lowerCamelCase_ = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' ,type=__UpperCamelCase ,default='bert-base-cased' ,help='Path to pretrained model or model identifier from huggingface.co/models.' ,required=__UpperCamelCase ,) parser.add_argument( '--output_dir' ,type=__UpperCamelCase ,default='.' ,help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' ,) parser.add_argument( '--resume_from_checkpoint' ,type=__UpperCamelCase ,default=__UpperCamelCase ,help='If the training should continue from a checkpoint folder.' ,) parser.add_argument( '--partial_train_epoch' ,type=__UpperCamelCase ,default=__UpperCamelCase ,help='If passed, the training will stop after this number of epochs.' ,) parser.add_argument( '--num_epochs' ,type=__UpperCamelCase ,default=2 ,help='Number of train epochs.' ,) lowerCamelCase_ = parser.parse_args() lowerCamelCase_ = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(__UpperCamelCase ,__UpperCamelCase ) if __name__ == "__main__": main()
42
1
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = None class UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 2 @register_to_config def __init__( self , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = 1.007 , SCREAMING_SNAKE_CASE_ = 80 , SCREAMING_SNAKE_CASE_ = 0.05 , SCREAMING_SNAKE_CASE_ = 50 , ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = sigma_max # setable values lowerCamelCase_ = None lowerCamelCase_ = None lowerCamelCase_ = None # sigma(t_i) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> torch.FloatTensor: '''simple docstring''' return sample def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Dict: '''simple docstring''' lowerCamelCase_ = num_inference_steps lowerCamelCase_ = np.arange(0 , self.num_inference_steps )[::-1].copy() lowerCamelCase_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] lowerCamelCase_ = torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa , device=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[torch.FloatTensor, float]: '''simple docstring''' if self.config.s_min <= sigma <= self.config.s_max: lowerCamelCase_ = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: lowerCamelCase_ = 0 # sample eps ~ N(0, S_noise^2 * I) lowerCamelCase_ = self.config.s_noise * randn_tensor(sample.shape , generator=SCREAMING_SNAKE_CASE_ ).to(sample.device ) lowerCamelCase_ = sigma + gamma * sigma lowerCamelCase_ = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , ) -> Union[KarrasVeOutput, Tuple]: '''simple docstring''' lowerCamelCase_ = sample_hat + sigma_hat * model_output lowerCamelCase_ = (sample_hat - pred_original_sample) / sigma_hat lowerCamelCase_ = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=SCREAMING_SNAKE_CASE_ , derivative=SCREAMING_SNAKE_CASE_ , pred_original_sample=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , ) -> Union[KarrasVeOutput, Tuple]: '''simple docstring''' lowerCamelCase_ = sample_prev + sigma_prev * model_output lowerCamelCase_ = (sample_prev - pred_original_sample) / sigma_prev lowerCamelCase_ = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=SCREAMING_SNAKE_CASE_ , derivative=SCREAMING_SNAKE_CASE_ , pred_original_sample=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' raise NotImplementedError()
42
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> np.ndarray: # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: lowerCamelCase_ = ksize + 1 lowerCamelCase_ = np.zeros((ksize, ksize) ,dtype=np.floataa ) # each value for y in range(__UpperCamelCase ): for x in range(__UpperCamelCase ): # distance from center lowerCamelCase_ = x - ksize // 2 lowerCamelCase_ = y - ksize // 2 # degree to radiant lowerCamelCase_ = theta / 1_80 * np.pi lowerCamelCase_ = np.cos(_theta ) lowerCamelCase_ = np.sin(_theta ) # get kernel x lowerCamelCase_ = cos_theta * px + sin_theta * py # get kernel y lowerCamelCase_ = -sin_theta * px + cos_theta * py # fill kernel lowerCamelCase_ = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image A_ = imread("../image_data/lena.jpg") # turn image in gray scale value A_ = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges A_ = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: A_ = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) A_ = out / out.max() * 255 A_ = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
42
1
'''simple docstring''' A_ = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", "\"": ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/" } # Exclamation mark is not in ITU-R recommendation # fmt: on A_ = {value: key for key, value in MORSE_CODE_DICT.items()} def _UpperCamelCase ( __UpperCamelCase ) -> str: return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def _UpperCamelCase ( __UpperCamelCase ) -> str: return "".join(REVERSE_DICT[char] for char in message.split() ) def _UpperCamelCase ( ) -> None: lowerCamelCase_ = 'Morse code here!' print(__UpperCamelCase ) lowerCamelCase_ = encrypt(__UpperCamelCase ) print(__UpperCamelCase ) lowerCamelCase_ = decrypt(__UpperCamelCase ) print(__UpperCamelCase ) if __name__ == "__main__": main()
42
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['transformers', 'torch', 'note_seq'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['transformers', 'torch', 'note_seq'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['transformers', 'torch', 'note_seq'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' requires_backends(cls , ['transformers', 'torch', 'note_seq'] )
42
1
'''simple docstring''' from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _UpperCamelCase ( ) -> List[Any]: lowerCamelCase_ = HfArgumentParser(__UpperCamelCase ) lowerCamelCase_ = parser.parse_args_into_dataclasses()[0] lowerCamelCase_ = TensorFlowBenchmark(args=__UpperCamelCase ) try: lowerCamelCase_ = parser.parse_args_into_dataclasses()[0] except ValueError as e: lowerCamelCase_ = 'Arg --no_{0} is no longer used, please use --no-{0} instead.' lowerCamelCase_ = ' '.join(str(__UpperCamelCase ).split(' ' )[:-1] ) lowerCamelCase_ = '' lowerCamelCase_ = eval(str(__UpperCamelCase ).split(' ' )[-1] ) lowerCamelCase_ = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: lowerCamelCase_ = full_error_msg + begin_error_msg + str(__UpperCamelCase ) raise ValueError(__UpperCamelCase ) benchmark.run() if __name__ == "__main__": main()
42
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def UpperCamelCase( self ) -> int: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , ) return model @property def UpperCamelCase( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) lowerCamelCase_ = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) lowerCamelCase_ = DDPMScheduler() lowerCamelCase_ = AudioDiffusionPipeline(vqvae=SCREAMING_SNAKE_CASE_ , unet=self.dummy_unet , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , steps=4 ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = output.images[0] lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , steps=4 , return_dict=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 lowerCamelCase_ = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) lowerCamelCase_ = DDIMScheduler() lowerCamelCase_ = self.dummy_vqvae_and_unet lowerCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) np.random.seed(0 ) lowerCamelCase_ = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(raw_audio=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , start_step=5 , steps=10 ) lowerCamelCase_ = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 lowerCamelCase_ = self.dummy_unet_condition lowerCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=SCREAMING_SNAKE_CASE_ , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) np.random.seed(0 ) lowerCamelCase_ = torch.rand((1, 1, 10) ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , encoding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.images[0] lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = torch_device lowerCamelCase_ = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
42
1
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset from utils import logger class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = params lowerCamelCase_ = np.array(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = np.array([len(SCREAMING_SNAKE_CASE_ ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' return (self.token_ids[index], self.lengths[index]) def __len__( self ) -> Any: '''simple docstring''' return len(self.lengths ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = self.params.max_model_input_size lowerCamelCase_ = self.lengths > max_len logger.info(f'''Splitting {sum(SCREAMING_SNAKE_CASE_ )} too long sequences.''' ) def divide_chunks(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return [l[i : i + n] for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )] lowerCamelCase_ = [] lowerCamelCase_ = [] if self.params.mlm: lowerCamelCase_ ,lowerCamelCase_ = self.params.special_tok_ids['cls_token'], self.params.special_tok_ids['sep_token'] else: lowerCamelCase_ ,lowerCamelCase_ = self.params.special_tok_ids['bos_token'], self.params.special_tok_ids['eos_token'] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: lowerCamelCase_ = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: lowerCamelCase_ = np.insert(SCREAMING_SNAKE_CASE_ , 0 , SCREAMING_SNAKE_CASE_ ) if sub_s[-1] != sep_id: lowerCamelCase_ = np.insert(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) assert len(SCREAMING_SNAKE_CASE_ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(SCREAMING_SNAKE_CASE_ ) new_tok_ids.extend(SCREAMING_SNAKE_CASE_ ) new_lengths.extend([len(SCREAMING_SNAKE_CASE_ ) for l in sub_seqs] ) lowerCamelCase_ = np.array(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = np.array(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = len(self ) lowerCamelCase_ = self.lengths > 11 lowerCamelCase_ = self.token_ids[indices] lowerCamelCase_ = self.lengths[indices] lowerCamelCase_ = len(self ) logger.info(f'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' if "unk_token" not in self.params.special_tok_ids: return else: lowerCamelCase_ = self.params.special_tok_ids['unk_token'] lowerCamelCase_ = len(self ) lowerCamelCase_ = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) lowerCamelCase_ = (unk_occs / self.lengths) < 0.5 lowerCamelCase_ = self.token_ids[indices] lowerCamelCase_ = self.lengths[indices] lowerCamelCase_ = len(self ) logger.info(f'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' if not self.params.is_master: return logger.info(f'''{len(self )} sequences''' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' lowerCamelCase_ = [t[0] for t in batch] lowerCamelCase_ = [t[1] for t in batch] assert len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ) # Max for paddings lowerCamelCase_ = max(SCREAMING_SNAKE_CASE_ ) # Pad token ids if self.params.mlm: lowerCamelCase_ = self.params.special_tok_ids['pad_token'] else: lowerCamelCase_ = self.params.special_tok_ids['unk_token'] lowerCamelCase_ = [list(t.astype(SCREAMING_SNAKE_CASE_ ) ) + [pad_idx] * (max_seq_len_ - len(SCREAMING_SNAKE_CASE_ )) for t in token_ids] assert len(tk_ ) == len(SCREAMING_SNAKE_CASE_ ) assert all(len(SCREAMING_SNAKE_CASE_ ) == max_seq_len_ for t in tk_ ) lowerCamelCase_ = torch.tensor(tk_ ) # (bs, max_seq_len_) lowerCamelCase_ = torch.tensor(SCREAMING_SNAKE_CASE_ ) # (bs) return tk_t, lg_t
42
'''simple docstring''' import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _UpperCamelCase ( __UpperCamelCase = 8 ) -> str: lowerCamelCase_ = ascii_letters + digits + punctuation return "".join(secrets.choice(__UpperCamelCase ) for _ in range(__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(__UpperCamelCase ) lowerCamelCase_ = i // 3 lowerCamelCase_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) lowerCamelCase_ = ( chars_incl + random(__UpperCamelCase ,quotient + remainder ) + random(__UpperCamelCase ,__UpperCamelCase ) + random(__UpperCamelCase ,__UpperCamelCase ) ) lowerCamelCase_ = list(__UpperCamelCase ) shuffle(__UpperCamelCase ) return "".join(__UpperCamelCase ) # random is a generalised function for letters, characters and numbers def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: return "".join(secrets.choice(__UpperCamelCase ) for _ in range(__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Optional[int]: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Tuple: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = 8 ) -> bool: if len(__UpperCamelCase ) < min_length: # Your Password must be at least 8 characters long return False lowerCamelCase_ = any(char in ascii_uppercase for char in password ) lowerCamelCase_ = any(char in ascii_lowercase for char in password ) lowerCamelCase_ = any(char in digits for char in password ) lowerCamelCase_ = 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 _UpperCamelCase ( ) -> Optional[int]: lowerCamelCase_ = int(input('Please indicate the max length of your password: ' ).strip() ) lowerCamelCase_ = input( 'Please indicate the characters that must be in your password: ' ).strip() print('Password generated:' ,password_generator(__UpperCamelCase ) ) print( 'Alternative Password generated:' ,alternative_password_generator(__UpperCamelCase ,__UpperCamelCase ) ,) print('[If you are thinking of using this passsword, You better save it.]' ) if __name__ == "__main__": main()
42
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
42
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 lowerCamelCase_ = test_metrics @require_cpu def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def UpperCamelCase( self ) -> Tuple: '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def UpperCamelCase( self ) -> Any: '''simple docstring''' self.test_metrics.main() @require_multi_gpu def UpperCamelCase( self ) -> Any: '''simple docstring''' print(f'''Found {torch.cuda.device_count()} devices.''' ) lowerCamelCase_ = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() )
42
1
'''simple docstring''' import os import string import sys A_ = 1 << 8 A_ = { "tab": ord("\t"), "newline": ord("\r"), "esc": 27, "up": 65 + ARROW_KEY_FLAG, "down": 66 + ARROW_KEY_FLAG, "right": 67 + ARROW_KEY_FLAG, "left": 68 + ARROW_KEY_FLAG, "mod_int": 91, "undefined": sys.maxsize, "interrupt": 3, "insert": 50, "delete": 51, "pg_up": 53, "pg_down": 54, } A_ = KEYMAP["up"] A_ = KEYMAP["left"] if sys.platform == "win32": A_ = [] A_ = { B"\xe0H": KEYMAP["up"] - ARROW_KEY_FLAG, B"\x00H": KEYMAP["up"] - ARROW_KEY_FLAG, B"\xe0P": KEYMAP["down"] - ARROW_KEY_FLAG, B"\x00P": KEYMAP["down"] - ARROW_KEY_FLAG, B"\xe0M": KEYMAP["right"] - ARROW_KEY_FLAG, B"\x00M": KEYMAP["right"] - ARROW_KEY_FLAG, B"\xe0K": KEYMAP["left"] - ARROW_KEY_FLAG, B"\x00K": KEYMAP["left"] - ARROW_KEY_FLAG, } for i in range(10): A_ = ord(str(i)) def _UpperCamelCase ( ) -> int: if os.name == "nt": import msvcrt lowerCamelCase_ = 'mbcs' # Flush the keyboard buffer while msvcrt.kbhit(): msvcrt.getch() if len(__UpperCamelCase ) == 0: # Read the keystroke lowerCamelCase_ = msvcrt.getch() # If it is a prefix char, get second part if ch in (b"\x00", b"\xe0"): lowerCamelCase_ = ch + msvcrt.getch() # Translate actual Win chars to bullet char types try: lowerCamelCase_ = chr(WIN_KEYMAP[cha] ) WIN_CH_BUFFER.append(chr(KEYMAP['mod_int'] ) ) WIN_CH_BUFFER.append(__UpperCamelCase ) if ord(__UpperCamelCase ) in ( KEYMAP["insert"] - 1 << 9, KEYMAP["delete"] - 1 << 9, KEYMAP["pg_up"] - 1 << 9, KEYMAP["pg_down"] - 1 << 9, ): WIN_CH_BUFFER.append(chr(1_26 ) ) lowerCamelCase_ = chr(KEYMAP['esc'] ) except KeyError: lowerCamelCase_ = cha[1] else: lowerCamelCase_ = ch.decode(__UpperCamelCase ) else: lowerCamelCase_ = WIN_CH_BUFFER.pop(0 ) elif os.name == "posix": import termios import tty lowerCamelCase_ = sys.stdin.fileno() lowerCamelCase_ = termios.tcgetattr(__UpperCamelCase ) try: tty.setraw(__UpperCamelCase ) lowerCamelCase_ = sys.stdin.read(1 ) finally: termios.tcsetattr(__UpperCamelCase ,termios.TCSADRAIN ,__UpperCamelCase ) return ch def _UpperCamelCase ( ) -> str: lowerCamelCase_ = get_raw_chars() if ord(__UpperCamelCase ) in [KEYMAP["interrupt"], KEYMAP["newline"]]: return char elif ord(__UpperCamelCase ) == KEYMAP["esc"]: lowerCamelCase_ = get_raw_chars() if ord(__UpperCamelCase ) == KEYMAP["mod_int"]: lowerCamelCase_ = get_raw_chars() if ord(__UpperCamelCase ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(__UpperCamelCase ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: return chr(ord(__UpperCamelCase ) + ARROW_KEY_FLAG ) else: return KEYMAP["undefined"] else: return get_raw_chars() else: if char in string.printable: return char else: return KEYMAP["undefined"]
42
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True) os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True) os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: if hor == 1_28: lowerCamelCase_ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') lowerCamelCase_ = (32, 1_28, 2_56) lowerCamelCase_ = ('UpResnetBlock1D', 'UpResnetBlock1D') elif hor == 32: lowerCamelCase_ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') lowerCamelCase_ = (32, 64, 1_28, 2_56) lowerCamelCase_ = ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D') lowerCamelCase_ = torch.load(f'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' ) lowerCamelCase_ = model.state_dict() lowerCamelCase_ = { 'down_block_types': down_block_types, 'block_out_channels': block_out_channels, 'up_block_types': up_block_types, 'layers_per_block': 1, 'use_timestep_embedding': True, 'out_block_type': 'OutConv1DBlock', 'norm_num_groups': 8, 'downsample_each_block': False, 'in_channels': 14, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'flip_sin_to_cos': False, 'freq_shift': 1, 'sample_size': 6_55_36, 'mid_block_type': 'MidResTemporalBlock1D', 'act_fn': 'mish', } lowerCamelCase_ = UNetaDModel(**__UpperCamelCase ) print(f'''length of state dict: {len(state_dict.keys() )}''' ) print(f'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) lowerCamelCase_ = dict(zip(model.state_dict().keys() ,hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): lowerCamelCase_ = state_dict.pop(__UpperCamelCase ) hf_value_function.load_state_dict(__UpperCamelCase ) torch.save(hf_value_function.state_dict() ,f'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' ) with open(f'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( ) -> Tuple: lowerCamelCase_ = { 'in_channels': 14, 'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'), 'up_block_types': (), 'out_block_type': 'ValueFunction', 'mid_block_type': 'ValueFunctionMidBlock1D', 'block_out_channels': (32, 64, 1_28, 2_56), 'layers_per_block': 1, 'downsample_each_block': True, 'sample_size': 6_55_36, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'use_timestep_embedding': True, 'flip_sin_to_cos': False, 'freq_shift': 1, 'norm_num_groups': 8, 'act_fn': 'mish', } lowerCamelCase_ = torch.load('/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch' ) lowerCamelCase_ = model lowerCamelCase_ = UNetaDModel(**__UpperCamelCase ) print(f'''length of state dict: {len(state_dict.keys() )}''' ) print(f'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) lowerCamelCase_ = dict(zip(state_dict.keys() ,hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): lowerCamelCase_ = state_dict.pop(__UpperCamelCase ) hf_value_function.load_state_dict(__UpperCamelCase ) torch.save(hf_value_function.state_dict() ,'hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin' ) with open('hub/hopper-medium-v2/value_function/config.json' ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) if __name__ == "__main__": unet(32) # unet(128) value_function()
42
1
'''simple docstring''' import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTokenizerFast from utils import get_device, get_timestamp, show_pil class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ = "cpu" , SCREAMING_SNAKE_CASE_ = "openai/clip-vit-large-patch14" ) -> None: '''simple docstring''' lowerCamelCase_ = device lowerCamelCase_ = CLIPTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = [0.48_145_466, 0.4_578_275, 0.40_821_073] lowerCamelCase_ = [0.26_862_954, 0.26_130_258, 0.27_577_711] lowerCamelCase_ = torchvision.transforms.Normalize(self.image_mean , self.image_std ) lowerCamelCase_ = torchvision.transforms.Resize(224 ) lowerCamelCase_ = torchvision.transforms.CenterCrop(224 ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.resize(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.center_crop(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.normalize(SCREAMING_SNAKE_CASE_ ) return images def __call__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.tokenizer(text=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.preprocess_img(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {key: value.to(self.device ) for (key, value) in encoding.items()} return encoding class UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0.01 , 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_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="image" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , ) -> None: '''simple docstring''' super().__init__() lowerCamelCase_ = None lowerCamelCase_ = device if device else get_device() if vqgan: lowerCamelCase_ = vqgan else: lowerCamelCase_ = load_vqgan(self.device , conf_path=SCREAMING_SNAKE_CASE_ , ckpt_path=SCREAMING_SNAKE_CASE_ ) self.vqgan.eval() if clip: lowerCamelCase_ = clip else: lowerCamelCase_ = CLIPModel.from_pretrained('openai/clip-vit-base-patch32' ) self.clip.to(self.device ) lowerCamelCase_ = ProcessorGradientFlow(device=self.device ) lowerCamelCase_ = iterations lowerCamelCase_ = lr lowerCamelCase_ = log lowerCamelCase_ = make_grid lowerCamelCase_ = return_val lowerCamelCase_ = quantize lowerCamelCase_ = self.vqgan.decoder.z_shape def UpperCamelCase( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=True ) -> Dict: '''simple docstring''' lowerCamelCase_ = [] if output_path is None: lowerCamelCase_ = './animation.gif' if input_path is None: lowerCamelCase_ = self.save_path lowerCamelCase_ = sorted(glob(input_path + '/*' ) ) if not len(SCREAMING_SNAKE_CASE_ ): raise ValueError( 'No images found in save path, aborting (did you pass save_intermediate=True to the generate' ' function?)' ) if len(SCREAMING_SNAKE_CASE_ ) == 1: print('Only one image found in save path, (did you pass save_intermediate=True to the generate function?)' ) lowerCamelCase_ = total_duration / len(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = [frame_duration] * len(SCREAMING_SNAKE_CASE_ ) if extend_frames: lowerCamelCase_ = 1.5 lowerCamelCase_ = 3 for file_name in paths: if file_name.endswith('.png' ): images.append(imageio.imread(SCREAMING_SNAKE_CASE_ ) ) imageio.mimsave(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , duration=SCREAMING_SNAKE_CASE_ ) print(f'''gif saved to {output_path}''' ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ) -> List[Any]: '''simple docstring''' if not (path or img): raise ValueError('Input either path or tensor' ) if img is not None: raise NotImplementedError lowerCamelCase_ = preprocess(Image.open(SCREAMING_SNAKE_CASE_ ) , target_image_size=256 ).to(self.device ) lowerCamelCase_ = preprocess_vqgan(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ ,*lowerCamelCase_ = self.vqgan.encode(SCREAMING_SNAKE_CASE_ ) return z def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.latent.detach().requires_grad_() lowerCamelCase_ = base_latent + transform_vector if self.quantize: lowerCamelCase_ ,*lowerCamelCase_ = self.vqgan.quantize(SCREAMING_SNAKE_CASE_ ) else: lowerCamelCase_ = trans_latent return self.vqgan.decode(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.clip_preprocessor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ , return_tensors='pt' , padding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.clip(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = clip_outputs.logits_per_image if weights is not None: lowerCamelCase_ = similarity_logits * weights return similarity_logits.sum() def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self._get_clip_similarity(pos_prompts['prompts'] , SCREAMING_SNAKE_CASE_ , weights=(1 / pos_prompts['weights']) ) if neg_prompts: lowerCamelCase_ = self._get_clip_similarity(neg_prompts['prompts'] , SCREAMING_SNAKE_CASE_ , weights=neg_prompts['weights'] ) else: lowerCamelCase_ = torch.tensor([1] , device=self.device ) lowerCamelCase_ = -torch.log(SCREAMING_SNAKE_CASE_ ) + torch.log(SCREAMING_SNAKE_CASE_ ) return loss def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' lowerCamelCase_ = torch.randn_like(self.latent , requires_grad=SCREAMING_SNAKE_CASE_ , device=self.device ) lowerCamelCase_ = torch.optim.Adam([vector] , lr=self.lr ) for i in range(self.iterations ): optim.zero_grad() lowerCamelCase_ = self._add_vector(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = loop_post_process(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self._get_CLIP_loss(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) print('CLIP loss' , SCREAMING_SNAKE_CASE_ ) if self.log: wandb.log({'CLIP Loss': clip_loss} ) clip_loss.backward(retain_graph=SCREAMING_SNAKE_CASE_ ) optim.step() if self.return_val == "image": yield custom_to_pil(transformed_img[0] ) else: yield vector def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' wandb.init(reinit=SCREAMING_SNAKE_CASE_ , project='face-editor' ) wandb.config.update({'Positive Prompts': positive_prompts} ) wandb.config.update({'Negative Prompts': negative_prompts} ) wandb.config.update({'lr': self.lr, 'iterations': self.iterations} ) if image_path: lowerCamelCase_ = Image.open(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = image.resize((256, 256) ) wandb.log('Original Image' , wandb.Image(SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' if not prompts: return [] lowerCamelCase_ = [] lowerCamelCase_ = [] if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [prompt.strip() for prompt in prompts.split('|' )] for prompt in prompts: if isinstance(SCREAMING_SNAKE_CASE_ , (tuple, list) ): lowerCamelCase_ = prompt[0] lowerCamelCase_ = float(prompt[1] ) elif ":" in prompt: lowerCamelCase_ ,lowerCamelCase_ = prompt.split(':' ) lowerCamelCase_ = float(SCREAMING_SNAKE_CASE_ ) else: lowerCamelCase_ = prompt lowerCamelCase_ = 1.0 processed_prompts.append(SCREAMING_SNAKE_CASE_ ) weights.append(SCREAMING_SNAKE_CASE_ ) return { "prompts": processed_prompts, "weights": torch.tensor(SCREAMING_SNAKE_CASE_ , device=self.device ), } def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> Union[str, Any]: '''simple docstring''' if image_path: lowerCamelCase_ = self._get_latent(SCREAMING_SNAKE_CASE_ ) else: lowerCamelCase_ = torch.randn(self.latent_dim , device=self.device ) if self.log: self._init_logging(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert pos_prompts, "You must provide at least one positive prompt." lowerCamelCase_ = self.process_prompts(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.process_prompts(SCREAMING_SNAKE_CASE_ ) if save_final and save_path is None: lowerCamelCase_ = os.path.join('./outputs/' , '_'.join(pos_prompts['prompts'] ) ) if not os.path.exists(SCREAMING_SNAKE_CASE_ ): os.makedirs(SCREAMING_SNAKE_CASE_ ) else: lowerCamelCase_ = save_path + '_' + get_timestamp() os.makedirs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = save_path lowerCamelCase_ = self.vqgan.decode(self.latent )[0] if show_intermediate: print('Original Image' ) show_pil(custom_to_pil(SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase_ = loop_post_process(SCREAMING_SNAKE_CASE_ ) for iter, transformed_img in enumerate(self._optimize_CLIP(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ): if show_intermediate: show_pil(SCREAMING_SNAKE_CASE_ ) if save_intermediate: transformed_img.save(os.path.join(self.save_path , f'''iter_{iter:03d}.png''' ) ) if self.log: wandb.log({'Image': wandb.Image(SCREAMING_SNAKE_CASE_ )} ) if show_final: show_pil(SCREAMING_SNAKE_CASE_ ) if save_final: transformed_img.save(os.path.join(self.save_path , f'''iter_{iter:03d}_final.png''' ) )
42
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, 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 A_ = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A_ = 250_004 A_ = 250_020 @require_sentencepiece @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = MBartTokenizer SCREAMING_SNAKE_CASE_ = MBartTokenizerFast SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase_ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase_ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def UpperCamelCase( self ) -> int: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase_ = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCamelCase_ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) lowerCamelCase_ = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=True lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=False lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'facebook/mbart-large-en-ro' SCREAMING_SNAKE_CASE_ = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] SCREAMING_SNAKE_CASE_ = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] SCREAMING_SNAKE_CASE_ = [82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2, EN_CODE] @classmethod def UpperCamelCase( cls ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) lowerCamelCase_ = 1 return cls def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 250020 ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' self.assertIn(SCREAMING_SNAKE_CASE_ , self.tokenizer.all_special_ids ) lowerCamelCase_ = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] lowerCamelCase_ = self.tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 10 lowerCamelCase_ = self.tokenizer(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [250026, 250001] ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = MBartTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) lowerCamelCase_ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=3 , return_tensors='pt' ) lowerCamelCase_ = self.tokenizer( text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=10 , return_tensors='pt' ) lowerCamelCase_ = targets['input_ids'] lowerCamelCase_ = shift_tokens_right(SCREAMING_SNAKE_CASE_ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ) , { # A, test, EOS, en_XX 'input_ids': [[62, 3034, 2, 250004]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 250001, } , )
42
1
'''simple docstring''' import string from math import logaa def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> int: lowerCamelCase_ = document.translate( str.maketrans('' ,'' ,string.punctuation ) ).replace('\n' ,'' ) lowerCamelCase_ = document_without_punctuation.split(' ' ) # word tokenization return len([word for word in tokenize_document if word.lower() == term.lower()] ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> tuple[int, int]: lowerCamelCase_ = corpus.lower().translate( str.maketrans('' ,'' ,string.punctuation ) ) # strip all punctuation and replace it with '' lowerCamelCase_ = corpus_without_punctuation.split('\n' ) lowerCamelCase_ = term.lower() return (len([doc for doc in docs if term in doc] ), len(__UpperCamelCase )) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=False ) -> float: if smoothing: if n == 0: raise ValueError('log10(0) is undefined.' ) return round(1 + logaa(n / (1 + df) ) ,3 ) if df == 0: raise ZeroDivisionError('df must be > 0' ) elif n == 0: raise ValueError('log10(0) is undefined.' ) return round(logaa(n / df ) ,3 ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> float: return round(tf * idf ,3 )
42
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = 'ylacombe/bark-small' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = 'en_speaker_1' lowerCamelCase_ = 'This is a test string' lowerCamelCase_ = 'speaker_embeddings_path.json' lowerCamelCase_ = 'speaker_embeddings' def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase_ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase_ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCamelCase_ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='(BOS)' , eos_token='(EOS)' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase_ = 35 lowerCamelCase_ = 2 lowerCamelCase_ = 8 lowerCamelCase_ = { 'semantic_prompt': np.ones(SCREAMING_SNAKE_CASE_ ), 'coarse_prompt': np.ones((nb_codebooks_coarse, seq_len) ), 'fine_prompt': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() ) # test loading voice preset from npz file lowerCamelCase_ = os.path.join(self.tmpdirname , 'file.npz' ) np.savez(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() ) # test loading voice preset from the hub lowerCamelCase_ = processor(text=self.input_string , voice_preset=self.voice_preset ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = processor(text=self.input_string ) lowerCamelCase_ = tokenizer( self.input_string , padding='max_length' , max_length=256 , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
42
1
'''simple docstring''' import math def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> float: if ( not isinstance(__UpperCamelCase ,(int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('power_factor must be a valid float value between -1 and 1.' ) return apparent_power * power_factor def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> float: if ( not isinstance(__UpperCamelCase ,(int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('power_factor must be a valid float value between -1 and 1.' ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
42
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} A_ = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } A_ = { "allenai/longformer-base-4096": 4_096, "allenai/longformer-large-4096": 4_096, "allenai/longformer-large-4096-finetuned-triviaqa": 4_096, "allenai/longformer-base-4096-extra.pos.embd.only": 4_096, "allenai/longformer-large-4096-extra.pos.embd.only": 4_096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _UpperCamelCase ( ) -> Any: lowerCamelCase_ = ( list(range(ord('!' ) ,ord('~' ) + 1 ) ) + list(range(ord('¡' ) ,ord('¬' ) + 1 ) ) + list(range(ord('®' ) ,ord('ÿ' ) + 1 ) ) ) lowerCamelCase_ = bs[:] lowerCamelCase_ = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 lowerCamelCase_ = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase ,__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: lowerCamelCase_ = set() lowerCamelCase_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCamelCase_ = char return pairs class UpperCAmelCase ( UpperCAmelCase__ ): '''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 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="replace" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else bos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else eos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else sep_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else cls_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else unk_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( errors=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as vocab_handle: lowerCamelCase_ = json.load(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {v: k for k, v in self.encoder.items()} lowerCamelCase_ = errors # how to handle errors in decoding lowerCamelCase_ = bytes_to_unicode() lowerCamelCase_ = {v: k for k, v in self.byte_encoder.items()} with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as merges_handle: lowerCamelCase_ = merges_handle.read().split('\n' )[1:-1] lowerCamelCase_ = [tuple(merge.split() ) for merge in bpe_merges] lowerCamelCase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowerCamelCase_ = {} lowerCamelCase_ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowerCamelCase_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' return len(self.encoder ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' if token in self.cache: return self.cache[token] lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) if not pairs: return token while True: lowerCamelCase_ = min(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break lowerCamelCase_ ,lowerCamelCase_ = bigram lowerCamelCase_ = [] lowerCamelCase_ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): try: lowerCamelCase_ = word.index(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCamelCase_ = j if word[i] == first and i < len(SCREAMING_SNAKE_CASE_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = new_word if len(SCREAMING_SNAKE_CASE_ ) == 1: break else: lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = ' '.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = word return word def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' lowerCamelCase_ = [] for token in re.findall(self.pat , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(SCREAMING_SNAKE_CASE_ ).split(' ' ) ) return bpe_tokens def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' return self.encoder.get(SCREAMING_SNAKE_CASE_ , self.encoder.get(self.unk_token ) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' return self.decoder.get(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = ''.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) + '\n' ) lowerCamelCase_ = 0 with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ' Please check that the tokenizer is not corrupted!' ) lowerCamelCase_ = token_index writer.write(' '.join(SCREAMING_SNAKE_CASE_ ) + '\n' ) index += 1 return vocab_file, merge_file def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] lowerCamelCase_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' lowerCamelCase_ = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(SCREAMING_SNAKE_CASE_ ) > 0 and not text[0].isspace()): lowerCamelCase_ = ' ' + text return (text, kwargs)
42
1
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> List[Any]: if height >= 1: move_tower(height - 1 ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) move_disk(__UpperCamelCase ,__UpperCamelCase ) move_tower(height - 1 ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Tuple: print('moving disk from' ,__UpperCamelCase ,'to' ,__UpperCamelCase ) def _UpperCamelCase ( ) -> Tuple: lowerCamelCase_ = int(input('Height of hanoi: ' ).strip() ) move_tower(__UpperCamelCase ,'A' ,'B' ,'C' ) if __name__ == "__main__": main()
42
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} A_ = { "vocab_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt" ), "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt", "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt", "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt", "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt", }, "tokenizer_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json" ), "google/realm-orqa-nq-openqa": ( "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-nq-reader": ( "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-openqa": ( "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-reader": ( "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json" ), }, } A_ = { "google/realm-cc-news-pretrained-embedder": 512, "google/realm-cc-news-pretrained-encoder": 512, "google/realm-cc-news-pretrained-scorer": 512, "google/realm-cc-news-pretrained-openqa": 512, "google/realm-orqa-nq-openqa": 512, "google/realm-orqa-nq-reader": 512, "google/realm-orqa-wq-openqa": 512, "google/realm-orqa-wq-reader": 512, } A_ = { "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-reader": {"do_lower_case": True}, "google/realm-orqa-wq-openqa": {"do_lower_case": True}, "google/realm-orqa-wq-reader": {"do_lower_case": True}, } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ = RealmTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="[UNK]" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="[PAD]" , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[MASK]" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> List[Any]: '''simple docstring''' super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , do_lower_case=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , SCREAMING_SNAKE_CASE_ ) != do_lower_case or normalizer_state.get('strip_accents' , SCREAMING_SNAKE_CASE_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , SCREAMING_SNAKE_CASE_ ) != tokenize_chinese_chars ): lowerCamelCase_ = getattr(SCREAMING_SNAKE_CASE_ , normalizer_state.pop('type' ) ) lowerCamelCase_ = do_lower_case lowerCamelCase_ = strip_accents lowerCamelCase_ = tokenize_chinese_chars lowerCamelCase_ = normalizer_class(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = do_lower_case def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = PaddingStrategy.MAX_LENGTH lowerCamelCase_ = text lowerCamelCase_ = kwargs.pop('text_pair' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = kwargs.pop('return_tensors' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'input_ids': [], 'attention_mask': [], 'token_type_ids': [], } for idx, candidate_text in enumerate(SCREAMING_SNAKE_CASE_ ): if batch_text_pair is not None: lowerCamelCase_ = batch_text_pair[idx] else: lowerCamelCase_ = None lowerCamelCase_ = super().__call__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = encoded_candidates.get('input_ids' ) lowerCamelCase_ = encoded_candidates.get('attention_mask' ) lowerCamelCase_ = encoded_candidates.get('token_type_ids' ) if encoded_input_ids is not None: output_data["input_ids"].append(SCREAMING_SNAKE_CASE_ ) if encoded_attention_mask is not None: output_data["attention_mask"].append(SCREAMING_SNAKE_CASE_ ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {key: item for key, item in output_data.items() if len(SCREAMING_SNAKE_CASE_ ) != 0} return BatchEncoding(SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' lowerCamelCase_ = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
42
1
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __UpperCamelCase ) -> bool: lowerCamelCase_ = len(__UpperCamelCase ) # We need to create solution object to save path. lowerCamelCase_ = [[0 for _ in range(__UpperCamelCase )] for _ in range(__UpperCamelCase )] lowerCamelCase_ = run_maze(__UpperCamelCase ,0 ,0 ,__UpperCamelCase ) if solved: print('\n'.join(str(__UpperCamelCase ) for row in solutions ) ) else: print('No solution exists!' ) return solved def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> bool: lowerCamelCase_ = len(__UpperCamelCase ) # Final check point. if i == j == (size - 1): lowerCamelCase_ = 1 return True lowerCamelCase_ = (not i < 0) and (not j < 0) # Check lower bounds lowerCamelCase_ = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. lowerCamelCase_ = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited lowerCamelCase_ = 1 # check for directions if ( run_maze(__UpperCamelCase ,i + 1 ,__UpperCamelCase ,__UpperCamelCase ) or run_maze(__UpperCamelCase ,__UpperCamelCase ,j + 1 ,__UpperCamelCase ) or run_maze(__UpperCamelCase ,i - 1 ,__UpperCamelCase ,__UpperCamelCase ) or run_maze(__UpperCamelCase ,__UpperCamelCase ,j - 1 ,__UpperCamelCase ) ): return True lowerCamelCase_ = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
42
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __UpperCamelCase ) -> bool: lowerCamelCase_ = str(__UpperCamelCase ) return len(__UpperCamelCase ) == 9 and set(__UpperCamelCase ) == set('123456789' ) def _UpperCamelCase ( ) -> int | None: for base_num in range(99_99 ,49_99 ,-1 ): lowerCamelCase_ = 10_00_02 * base_num if is_9_pandigital(__UpperCamelCase ): return candidate for base_num in range(3_33 ,99 ,-1 ): lowerCamelCase_ = 1_00_20_03 * base_num if is_9_pandigital(__UpperCamelCase ): return candidate return None if __name__ == "__main__": print(f'''{solution() = }''')
42
1
'''simple docstring''' import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=None ,__UpperCamelCase=None ,__UpperCamelCase=None ,__UpperCamelCase=None ,__UpperCamelCase=None ,) -> List[Any]: if attention_mask is None: lowerCamelCase_ = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: lowerCamelCase_ = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: lowerCamelCase_ = torch.ones(config.encoder_layers ,config.encoder_attention_heads ,device=__UpperCamelCase ) if decoder_head_mask is None: lowerCamelCase_ = torch.ones(config.decoder_layers ,config.decoder_attention_heads ,device=__UpperCamelCase ) if cross_attn_head_mask is None: lowerCamelCase_ = torch.ones(config.decoder_layers ,config.decoder_attention_heads ,device=__UpperCamelCase ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="relu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=20 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = parent lowerCamelCase_ = batch_size lowerCamelCase_ = seq_length lowerCamelCase_ = is_training lowerCamelCase_ = use_labels lowerCamelCase_ = vocab_size lowerCamelCase_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = num_attention_heads lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = encoder_layerdrop lowerCamelCase_ = decoder_layerdrop lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = eos_token_id lowerCamelCase_ = pad_token_id lowerCamelCase_ = bos_token_id def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_ = self.eos_token_id # Eos Token lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for M2M100 the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input lowerCamelCase_ = input_ids.clamp(self.pad_token_id + 1 ) lowerCamelCase_ = decoder_input_ids.clamp(self.pad_token_id + 1 ) lowerCamelCase_ = self.get_config() lowerCamelCase_ = prepare_mam_aaa_inputs_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return config, inputs_dict def UpperCamelCase( self ) -> Tuple: '''simple docstring''' return MaMaaaConfig( 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 , encoder_layerdrop=self.encoder_layerdrop , decoder_layerdrop=self.decoder_layerdrop , 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 , ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.prepare_config_and_inputs() return config, inputs_dict def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = MaMaaaModel(config=SCREAMING_SNAKE_CASE_ ).get_decoder().to(SCREAMING_SNAKE_CASE_ ).eval() lowerCamelCase_ = inputs_dict['input_ids'] lowerCamelCase_ = inputs_dict['attention_mask'] lowerCamelCase_ = inputs_dict['head_mask'] # first forward pass lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , head_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ ,lowerCamelCase_ = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids lowerCamelCase_ = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCamelCase_ = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and lowerCamelCase_ = torch.cat([input_ids, next_tokens] , dim=-1 ) lowerCamelCase_ = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )['last_hidden_state'] lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ )[ 'last_hidden_state' ] # select random slice lowerCamelCase_ = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowerCamelCase_ = output_from_no_past[:, -3:, random_slice_idx].detach() lowerCamelCase_ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-2 ) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' lowerCamelCase_ = MaMaaaModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() lowerCamelCase_ = model(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = outputs.encoder_last_hidden_state lowerCamelCase_ = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase_ = model.get_encoder() encoder.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = MaMaaaEncoder.from_pretrained(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = encoder(inputs_dict['input_ids'] , attention_mask=inputs_dict['attention_mask'] )[ 0 ] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase_ = model.get_decoder() decoder.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = MaMaaaDecoder.from_pretrained(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = decoder( input_ids=inputs_dict['decoder_input_ids'] , attention_mask=inputs_dict['decoder_attention_mask'] , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=inputs_dict['attention_mask'] , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ( ( MaMaaaModel, MaMaaaForConditionalGeneration, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ = (MaMaaaForConditionalGeneration,) if is_torch_available() else () SCREAMING_SNAKE_CASE_ = ( { 'conversational': MaMaaaForConditionalGeneration, 'feature-extraction': MaMaaaModel, 'summarization': MaMaaaForConditionalGeneration, 'text2text-generation': MaMaaaForConditionalGeneration, 'translation': MaMaaaForConditionalGeneration, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' if pipeline_test_casse_name == "TranslationPipelineTests": # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`. # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer. return True return False def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = MaMaaaModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: lowerCamelCase_ = model_class(SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ ,lowerCamelCase_ = model_class.from_pretrained(SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ ) self.assertEqual(info['missing_keys'] , [] ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration): lowerCamelCase_ = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = copy.deepcopy(self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) if not self.is_encoder_decoder: lowerCamelCase_ = inputs['input_ids'] del inputs["input_ids"] else: lowerCamelCase_ = inputs['input_ids'] lowerCamelCase_ = inputs.get('decoder_input_ids' , SCREAMING_SNAKE_CASE_ ) del inputs["input_ids"] inputs.pop('decoder_input_ids' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model.get_input_embeddings() if not self.is_encoder_decoder: lowerCamelCase_ = wte(SCREAMING_SNAKE_CASE_ ) else: lowerCamelCase_ = wte(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = wte(SCREAMING_SNAKE_CASE_ ) with torch.no_grad(): model(**SCREAMING_SNAKE_CASE_ )[0] def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() lowerCamelCase_ = input_dict['input_ids'] lowerCamelCase_ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = MaMaaaForConditionalGeneration(SCREAMING_SNAKE_CASE_ ).eval().to(SCREAMING_SNAKE_CASE_ ) if torch_device == "cuda": model.half() model.generate(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) model.generate(num_beams=4 , do_sample=SCREAMING_SNAKE_CASE_ , early_stopping=SCREAMING_SNAKE_CASE_ , num_return_sequences=3 ) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: return torch.tensor(__UpperCamelCase ,dtype=torch.long ,device=__UpperCamelCase ) A_ = 1E-4 @require_torch @require_sentencepiece @require_tokenizers @slow class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M' ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = MaMaaaModel.from_pretrained('facebook/m2m100_418M' ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]] ) lowerCamelCase_ = _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]] ) lowerCamelCase_ = prepare_mam_aaa_inputs_dict(model.config , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with torch.no_grad(): lowerCamelCase_ = model(**SCREAMING_SNAKE_CASE_ )[0] lowerCamelCase_ = torch.Size((1, 11, 1024) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) # change to expected output here lowerCamelCase_ = torch.tensor( [[-0.7_780, -0.1_676, 0.1_038], [-6.7_556, -1.3_992, 0.0_567], [-7.5_383, -0.5_920, -0.2_779]] , device=SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M' ).to(SCREAMING_SNAKE_CASE_ ) # change to intended input lowerCamelCase_ = _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]] ) lowerCamelCase_ = _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]] ) lowerCamelCase_ = prepare_mam_aaa_inputs_dict(model.config , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with torch.no_grad(): lowerCamelCase_ = model(**SCREAMING_SNAKE_CASE_ )[0] lowerCamelCase_ = torch.Size((1, 11, model.config.vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) # change to expected output here lowerCamelCase_ = torch.tensor( [[-1.0_448, -1.0_411, 3.7_992], [-3.2_191, -3.2_386, -1.3_451], [-3.6_210, -3.5_993, 0.4_925]] , device=SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M' ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M' , src_lang='fr' , tgt_lang='en' ) lowerCamelCase_ = [ 'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement', 'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.', 'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent' ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de' ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.', ] # The below article tests that we don't add any hypotheses outside of the top n_beams lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) lowerCamelCase_ = model.generate( input_ids=dct['input_ids'].to(SCREAMING_SNAKE_CASE_ ) , attention_mask=dct['attention_mask'].to(SCREAMING_SNAKE_CASE_ ) , num_beams=5 , forced_bos_token_id=tokenizer.get_lang_id('en' ) , ) lowerCamelCase_ = [ 'The NSA case highlights the total absence of intelligence debate', 'I think there are two levels of response from the French government.', 'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.' ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all' ' communications in France.', ] lowerCamelCase_ = tokenizer.batch_decode( hypotheses_batch.tolist() , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) assert generated == expected_en
42
'''simple docstring''' A_ = "Input must be a string of 8 numbers plus letter" A_ = "TRWAGMYFPDXBNJZSQVHLCKE" def _UpperCamelCase ( __UpperCamelCase ) -> bool: if not isinstance(__UpperCamelCase ,__UpperCamelCase ): lowerCamelCase_ = f'''Expected string as input, found {type(__UpperCamelCase ).__name__}''' raise TypeError(__UpperCamelCase ) lowerCamelCase_ = spanish_id.replace('-' ,'' ).upper() if len(__UpperCamelCase ) != 9: raise ValueError(__UpperCamelCase ) try: lowerCamelCase_ = int(spanish_id_clean[0:8] ) lowerCamelCase_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(__UpperCamelCase ) from ex if letter.isdigit(): raise ValueError(__UpperCamelCase ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
42
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "microsoft/trocr-base-handwritten": ( "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'trocr' SCREAMING_SNAKE_CASE_ = ['past_key_values'] SCREAMING_SNAKE_CASE_ = { 'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model', 'num_hidden_layers': 'decoder_layers', } def __init__( self , SCREAMING_SNAKE_CASE_=50265 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = vocab_size lowerCamelCase_ = d_model lowerCamelCase_ = decoder_layers lowerCamelCase_ = decoder_attention_heads lowerCamelCase_ = decoder_ffn_dim lowerCamelCase_ = activation_function lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = init_std lowerCamelCase_ = decoder_layerdrop lowerCamelCase_ = use_cache lowerCamelCase_ = scale_embedding lowerCamelCase_ = use_learned_position_embeddings lowerCamelCase_ = layernorm_embedding super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
42
'''simple docstring''' import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = GPTSanJapaneseTokenizer SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = {'do_clean_text': False, 'add_prefix_space': False} def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' super().setUp() # fmt: off lowerCamelCase_ = ['こん', 'こんに', 'にちは', 'ばんは', '世界,㔺界', '、', '。', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on lowerCamelCase_ = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # 😀 lowerCamelCase_ = {'unk_token': '<unk>'} lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、世界。😀' return input_text, output_text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.get_input_output_texts(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ ) return text, ids def UpperCamelCase( self ) -> Tuple: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。 こんばんは、㔺界。' lowerCamelCase_ = ['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。'] lowerCamelCase_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids without special tokens lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids with special tokens lowerCamelCase_ = tokens + [tokenizer.unk_token] lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。' lowerCamelCase_ = 'こんにちは、、、、世界。こんばんは、、、、世界。' lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。こんばんは、世界。😀' lowerCamelCase_ = tokenizer.encode(prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode('' , prefix_text=prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = [1] + [0] * (len_prefix + len_text + 1) lowerCamelCase_ = [1] * (len_prefix + len_text + 1) + [0] lowerCamelCase_ = [1] + [1] * (len_prefix) + [0] * (len_text + 1) lowerCamelCase_ = tokenizer(prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = tokenizer.encode('あンいワ' ) lowerCamelCase_ = tokenizer.encode('' , prefix_text='あンいワ' ) lowerCamelCase_ = tokenizer.encode('いワ' , prefix_text='あン' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = [['武田信玄', 'は、'], ['織田信長', 'の配下の、']] lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) # fmt: off lowerCamelCase_ = [[35993, 8640, 25948, 35998, 30647, 35675, 35999, 35999], [35993, 10382, 9868, 35998, 30646, 9459, 30646, 35675]] lowerCamelCase_ = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] lowerCamelCase_ = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass
42
1
'''simple docstring''' # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def _UpperCamelCase ( *__UpperCamelCase ) -> Dict: with open(__UpperCamelCase ,'r' ) as fh: fcntl.flock(__UpperCamelCase ,fcntl.LOCK_EX ) try: print(*__UpperCamelCase ) finally: fcntl.flock(__UpperCamelCase ,fcntl.LOCK_UN ) A_ = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) A_ = torch.device("cuda", local_rank) A_ = socket.gethostname() A_ = f'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group("nccl") dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank A_ = dist.get_rank() A_ = dist.get_world_size() printflock(f'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(f'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(f'''{gpu} is broken''') raise
42
'''simple docstring''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Dict: '''simple docstring''' super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> List[str]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory lowerCamelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> List[str]: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}''' ) 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 (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(SCREAMING_SNAKE_CASE_ )}.''' ) # get prompt text embeddings lowerCamelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=self.tokenizer.model_max_length , return_tensors='pt' , ) lowerCamelCase_ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowerCamelCase_ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( 'The following part of your input was truncated because CLIP can only handle sequences up to' f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) lowerCamelCase_ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: lowerCamelCase_ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = text_embeddings.shape lowerCamelCase_ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) lowerCamelCase_ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # 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. lowerCamelCase_ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: lowerCamelCase_ = 42 if negative_prompt is None: lowerCamelCase_ = [''] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( f'''`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=''' f''' {type(SCREAMING_SNAKE_CASE_ )}.''' ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( f'''`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:''' f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' ' the batch size of `prompt`.' ) else: lowerCamelCase_ = negative_prompt lowerCamelCase_ = text_input_ids.shape[-1] lowerCamelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='pt' , ) lowerCamelCase_ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCamelCase_ = uncond_embeddings.shape[1] lowerCamelCase_ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) lowerCamelCase_ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCamelCase_ = 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`. lowerCamelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) lowerCamelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) lowerCamelCase_ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps lowerCamelCase_ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='cpu' , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) lowerCamelCase_ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='cpu' , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: lowerCamelCase_ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) lowerCamelCase_ = latents_reference.to(self.device ) lowerCamelCase_ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images lowerCamelCase_ = (latents_shape[3] - latents_shape_reference[3]) // 2 lowerCamelCase_ = (latents_shape[2] - latents_shape_reference[2]) // 2 lowerCamelCase_ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx lowerCamelCase_ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy lowerCamelCase_ = 0 if dx < 0 else dx lowerCamelCase_ = 0 if dy < 0 else dy lowerCamelCase_ = max(-dx , 0 ) lowerCamelCase_ = max(-dy , 0 ) # import pdb # pdb.set_trace() lowerCamelCase_ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand lowerCamelCase_ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ = 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] lowerCamelCase_ = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ = {} if accepts_eta: lowerCamelCase_ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance lowerCamelCase_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCamelCase_ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual lowerCamelCase_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: lowerCamelCase_ ,lowerCamelCase_ = noise_pred.chunk(2 ) lowerCamelCase_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 1 / 0.18_215 * latents lowerCamelCase_ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample lowerCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: lowerCamelCase_ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors='pt' ).to( self.device ) lowerCamelCase_ ,lowerCamelCase_ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: lowerCamelCase_ = None if output_type == "pil": lowerCamelCase_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
42
1
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def _UpperCamelCase ( __UpperCamelCase ) -> List[Any]: lowerCamelCase_ ,lowerCamelCase_ = image.size lowerCamelCase_ ,lowerCamelCase_ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 lowerCamelCase_ = image.resize((w, h) ,resample=PIL_INTERPOLATION['lanczos'] ) lowerCamelCase_ = np.array(__UpperCamelCase ).astype(np.floataa ) / 255.0 lowerCamelCase_ = image[None].transpose(0 ,3 ,1 ,2 ) lowerCamelCase_ = torch.from_numpy(__UpperCamelCase ) return 2.0 * image - 1.0 class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: '''simple docstring''' super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): lowerCamelCase_ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): lowerCamelCase_ = image.shape[0] else: raise ValueError(f'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}''' ) if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): lowerCamelCase_ = preprocess(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ ,lowerCamelCase_ = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image lowerCamelCase_ = (batch_size, self.unet.config.in_channels // 2, height, width) lowerCamelCase_ = next(self.unet.parameters() ).dtype lowerCamelCase_ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = image.to(device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=self.device ) lowerCamelCase_ = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ = 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] lowerCamelCase_ = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ = {} if accepts_eta: lowerCamelCase_ = eta for t in self.progress_bar(SCREAMING_SNAKE_CASE_ ): # concat latents and low resolution image in the channel dimension. lowerCamelCase_ = torch.cat([latents, image] , dim=1 ) lowerCamelCase_ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual lowerCamelCase_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # decode the image latents with the VQVAE lowerCamelCase_ = self.vqvae.decode(SCREAMING_SNAKE_CASE_ ).sample lowerCamelCase_ = torch.clamp(SCREAMING_SNAKE_CASE_ , -1.0 , 1.0 ) lowerCamelCase_ = image / 2 + 0.5 lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCamelCase_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
42
'''simple docstring''' import pprint import requests A_ = "https://zenquotes.io/api" def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/today' ).json() def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": A_ = random_quotes() pprint.pprint(response)
42
1
'''simple docstring''' import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = GPTSanJapaneseTokenizer SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = {'do_clean_text': False, 'add_prefix_space': False} def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' super().setUp() # fmt: off lowerCamelCase_ = ['こん', 'こんに', 'にちは', 'ばんは', '世界,㔺界', '、', '。', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on lowerCamelCase_ = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # 😀 lowerCamelCase_ = {'unk_token': '<unk>'} lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、世界。😀' return input_text, output_text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.get_input_output_texts(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ ) return text, ids def UpperCamelCase( self ) -> Tuple: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。 こんばんは、㔺界。' lowerCamelCase_ = ['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。'] lowerCamelCase_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids without special tokens lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids with special tokens lowerCamelCase_ = tokens + [tokenizer.unk_token] lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。' lowerCamelCase_ = 'こんにちは、、、、世界。こんばんは、、、、世界。' lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。こんばんは、世界。😀' lowerCamelCase_ = tokenizer.encode(prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode('' , prefix_text=prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = [1] + [0] * (len_prefix + len_text + 1) lowerCamelCase_ = [1] * (len_prefix + len_text + 1) + [0] lowerCamelCase_ = [1] + [1] * (len_prefix) + [0] * (len_text + 1) lowerCamelCase_ = tokenizer(prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = tokenizer.encode('あンいワ' ) lowerCamelCase_ = tokenizer.encode('' , prefix_text='あンいワ' ) lowerCamelCase_ = tokenizer.encode('いワ' , prefix_text='あン' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = [['武田信玄', 'は、'], ['織田信長', 'の配下の、']] lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) # fmt: off lowerCamelCase_ = [[35993, 8640, 25948, 35998, 30647, 35675, 35999, 35999], [35993, 10382, 9868, 35998, 30646, 9459, 30646, 35675]] lowerCamelCase_ = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] lowerCamelCase_ = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass
42
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=33 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ) -> int: '''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_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = num_attention_heads lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = type_vocab_size lowerCamelCase_ = type_sequence_label_size lowerCamelCase_ = initializer_range lowerCamelCase_ = num_labels lowerCamelCase_ = num_choices lowerCamelCase_ = scope def UpperCamelCase( self ) -> str: '''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 lowerCamelCase_ = None lowerCamelCase_ = None if self.use_labels: lowerCamelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase_ = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase_ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase( self ) -> List[str]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = EsmModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = EsmForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' lowerCamelCase_ = self.num_labels lowerCamelCase_ = EsmForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) = config_and_inputs lowerCamelCase_ = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ = () SCREAMING_SNAKE_CASE_ = ( { 'feature-extraction': EsmModel, 'fill-mask': EsmForMaskedLM, 'text-classification': EsmForSequenceClassification, 'token-classification': EsmForTokenClassification, 'zero-shot': EsmForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = EsmModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> str: '''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(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ = EsmModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()[0] lowerCamelCase_ = EsmEmbeddings(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) lowerCamelCase_ = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) lowerCamelCase_ = create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE_ , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()[0] lowerCamelCase_ = EsmEmbeddings(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.empty(2 , 4 , 30 ) lowerCamelCase_ = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] lowerCamelCase_ = torch.as_tensor([expected_single_positions, expected_single_positions] ) lowerCamelCase_ = embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE_ ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) @unittest.skip('Esm does not support embedding resizing' ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' pass @unittest.skip('Esm does not support embedding resizing' ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass @require_torch class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' with torch.no_grad(): lowerCamelCase_ = EsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() lowerCamelCase_ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )[0] lowerCamelCase_ = 33 lowerCamelCase_ = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCamelCase( self ) -> Tuple: '''simple docstring''' with torch.no_grad(): lowerCamelCase_ = EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() lowerCamelCase_ = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )[0] # compare the actual values for a slice. lowerCamelCase_ = torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
42
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) A_ = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["OwlViTFeatureExtractor"] A_ = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
42
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A_ = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
42
1
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase ) -> list: if len(__UpperCamelCase ) <= 1: return [tuple(__UpperCamelCase )] lowerCamelCase_ = [] def generate(__UpperCamelCase ,__UpperCamelCase ): lowerCamelCase_ = [0] * n res.append(tuple(__UpperCamelCase ) ) lowerCamelCase_ = 0 while i < n: if c[i] < i: if i % 2 == 0: lowerCamelCase_ ,lowerCamelCase_ = arr[i], arr[0] else: lowerCamelCase_ ,lowerCamelCase_ = arr[i], arr[c[i]] res.append(tuple(__UpperCamelCase ) ) c[i] += 1 lowerCamelCase_ = 0 else: lowerCamelCase_ = 0 i += 1 generate(len(__UpperCamelCase ) ,__UpperCamelCase ) return res if __name__ == "__main__": A_ = input("Enter numbers separated by a comma:\n").strip() A_ = [int(item) for item in user_input.split(",")] print(heaps(arr))
42
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json" ), } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'xlm-prophetnet' SCREAMING_SNAKE_CASE_ = ['past_key_values'] SCREAMING_SNAKE_CASE_ = { 'num_attention_heads': 'num_encoder_attention_heads', } def __init__( self , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = "gelu" , SCREAMING_SNAKE_CASE_ = 30522 , SCREAMING_SNAKE_CASE_ = 1024 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 2 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 128 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 2 , **SCREAMING_SNAKE_CASE_ , ) -> Tuple: '''simple docstring''' lowerCamelCase_ = vocab_size lowerCamelCase_ = hidden_size lowerCamelCase_ = encoder_ffn_dim lowerCamelCase_ = num_encoder_layers lowerCamelCase_ = num_encoder_attention_heads lowerCamelCase_ = decoder_ffn_dim lowerCamelCase_ = num_decoder_layers lowerCamelCase_ = num_decoder_attention_heads lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = init_std # Normal(0, this parameter) lowerCamelCase_ = activation_function # parameters for xlmprophetnet lowerCamelCase_ = ngram lowerCamelCase_ = num_buckets lowerCamelCase_ = relative_max_distance lowerCamelCase_ = disable_ngram_loss lowerCamelCase_ = eps # 3 Types of Dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = dropout lowerCamelCase_ = use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , add_cross_attention=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @property def UpperCamelCase( self ) -> int: '''simple docstring''' return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' raise NotImplementedError( 'This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and' ' `num_decoder_layers`.' )
42
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'timm_backbone' def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> str: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = backbone lowerCamelCase_ = num_channels lowerCamelCase_ = features_only lowerCamelCase_ = use_pretrained_backbone lowerCamelCase_ = True lowerCamelCase_ = out_indices if out_indices is not None else (-1,)
42
'''simple docstring''' import colorsys from PIL import Image # type: ignore def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> float: lowerCamelCase_ = x lowerCamelCase_ = y for step in range(__UpperCamelCase ): # noqa: B007 lowerCamelCase_ = a * a - b * b + x lowerCamelCase_ = 2 * a * b + y lowerCamelCase_ = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _UpperCamelCase ( __UpperCamelCase ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _UpperCamelCase ( __UpperCamelCase ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(__UpperCamelCase ,1 ,1 ) ) def _UpperCamelCase ( __UpperCamelCase = 8_00 ,__UpperCamelCase = 6_00 ,__UpperCamelCase = -0.6 ,__UpperCamelCase = 0 ,__UpperCamelCase = 3.2 ,__UpperCamelCase = 50 ,__UpperCamelCase = True ,) -> Image.Image: lowerCamelCase_ = Image.new('RGB' ,(image_width, image_height) ) lowerCamelCase_ = img.load() # loop through the image-coordinates for image_x in range(__UpperCamelCase ): for image_y in range(__UpperCamelCase ): # determine the figure-coordinates based on the image-coordinates lowerCamelCase_ = figure_width / image_width * image_height lowerCamelCase_ = figure_center_x + (image_x / image_width - 0.5) * figure_width lowerCamelCase_ = figure_center_y + (image_y / image_height - 0.5) * figure_height lowerCamelCase_ = get_distance(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: lowerCamelCase_ = get_color_coded_rgb(__UpperCamelCase ) else: lowerCamelCase_ = get_black_and_white_rgb(__UpperCamelCase ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure A_ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
42
1
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase ) -> set: lowerCamelCase_ = set() # edges = list of graph's edges lowerCamelCase_ = get_edges(__UpperCamelCase ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: lowerCamelCase_ ,lowerCamelCase_ = edges.pop() chosen_vertices.add(__UpperCamelCase ) chosen_vertices.add(__UpperCamelCase ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(__UpperCamelCase ) return chosen_vertices def _UpperCamelCase ( __UpperCamelCase ) -> set: lowerCamelCase_ = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
42
'''simple docstring''' from math import isclose, sqrt def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> tuple[float, float, float]: lowerCamelCase_ = point_y / 4 / point_x lowerCamelCase_ = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) lowerCamelCase_ = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) lowerCamelCase_ = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 lowerCamelCase_ = outgoing_gradient**2 + 4 lowerCamelCase_ = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) lowerCamelCase_ = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 lowerCamelCase_ = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) lowerCamelCase_ = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point lowerCamelCase_ = x_minus if isclose(__UpperCamelCase ,__UpperCamelCase ) else x_plus lowerCamelCase_ = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _UpperCamelCase ( __UpperCamelCase = 1.4 ,__UpperCamelCase = -9.6 ) -> int: lowerCamelCase_ = 0 lowerCamelCase_ = first_x_coord lowerCamelCase_ = first_y_coord lowerCamelCase_ = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = next_point(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
42
1
'''simple docstring''' from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import PriorTransformer from .ta_film_transformer import TaFilmDecoder from .transformer_ad import TransformeraDModel from .unet_ad import UNetaDModel from .unet_ad import UNetaDModel from .unet_ad_condition import UNetaDConditionModel from .unet_ad_condition import UNetaDConditionModel from .vq_model import VQModel if is_flax_available(): from .controlnet_flax import FlaxControlNetModel from .unet_ad_condition_flax import FlaxUNetaDConditionModel from .vae_flax import FlaxAutoencoderKL
42
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = False ) -> bool: if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3_31_70_44_06_46_79_88_73_85_96_19_81 and not allow_probable: raise ValueError( 'Warning: upper bound of deterministic test is exceeded. ' 'Pass allow_probable=True to allow probabilistic test. ' 'A return value of True indicates a probable prime.' ) # array bounds provided by analysis lowerCamelCase_ = [ 20_47, 1_37_36_53, 25_32_60_01, 32_15_03_17_51, 2_15_23_02_89_87_47, 3_47_47_49_66_03_83, 3_41_55_00_71_72_83_21, 1, 3_82_51_23_05_65_46_41_30_51, 1, 1, 31_86_65_85_78_34_03_11_51_16_74_61, 3_31_70_44_06_46_79_88_73_85_96_19_81, ] lowerCamelCase_ = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(__UpperCamelCase ,1 ): if n < _p: # then we have our last prime to check lowerCamelCase_ = primes[:idx] break lowerCamelCase_ ,lowerCamelCase_ = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: lowerCamelCase_ = False for r in range(__UpperCamelCase ): lowerCamelCase_ = pow(__UpperCamelCase ,d * 2**r ,__UpperCamelCase ) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): lowerCamelCase_ = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True def _UpperCamelCase ( ) -> None: assert not miller_rabin(5_61 ) assert miller_rabin(5_63 ) # 2047 assert not miller_rabin(83_82_01 ) assert miller_rabin(83_82_07 ) # 1_373_653 assert not miller_rabin(17_31_60_01 ) assert miller_rabin(17_31_60_17 ) # 25_326_001 assert not miller_rabin(30_78_38_66_41 ) assert miller_rabin(30_78_38_66_53 ) # 3_215_031_751 assert not miller_rabin(1_71_30_45_57_48_01 ) assert miller_rabin(1_71_30_45_57_48_19 ) # 2_152_302_898_747 assert not miller_rabin(2_77_97_99_72_83_07 ) assert miller_rabin(2_77_97_99_72_83_27 ) # 3_474_749_660_383 assert not miller_rabin(1_13_85_00_23_90_94_41 ) assert miller_rabin(1_13_85_00_23_90_95_27 ) # 341_550_071_728_321 assert not miller_rabin(1_27_50_41_01_88_48_80_43_51 ) assert miller_rabin(1_27_50_41_01_88_48_80_43_91 ) # 3_825_123_056_546_413_051 assert not miller_rabin(7_96_66_46_44_58_50_77_87_79_18_67 ) assert miller_rabin(7_96_66_46_44_58_50_77_87_79_19_51 ) # 318_665_857_834_031_151_167_461 assert not miller_rabin(55_28_40_67_74_46_64_78_97_66_03_33 ) assert miller_rabin(55_28_40_67_74_46_64_78_97_66_03_59 ) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
42
1
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = None # Automatically constructed SCREAMING_SNAKE_CASE_ = "dict" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = field(default='Translation' , init=UpperCAmelCase__ , repr=UpperCAmelCase__ ) def __call__( self ) -> Optional[Any]: '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def UpperCamelCase( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value return {k: Value('string' ) for k in sorted(self.languages )} @dataclass class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None # Automatically constructed SCREAMING_SNAKE_CASE_ = "dict" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = field(default='TranslationVariableLanguages' , init=UpperCAmelCase__ , repr=UpperCAmelCase__ ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = sorted(set(self.languages ) ) if self.languages else None lowerCamelCase_ = len(self.languages ) if self.languages else None def __call__( self ) -> Dict: '''simple docstring''' return pa.struct({'language': pa.list_(pa.string() ), 'translation': pa.list_(pa.string() )} ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' lowerCamelCase_ = set(self.languages ) if self.languages and set(SCREAMING_SNAKE_CASE_ ) - lang_set: raise ValueError( f'''Some languages in example ({", ".join(sorted(set(SCREAMING_SNAKE_CASE_ ) - lang_set ) )}) are not in valid set ({", ".join(SCREAMING_SNAKE_CASE_ )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. lowerCamelCase_ = [] for lang, text in translation_dict.items(): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. lowerCamelCase_ ,lowerCamelCase_ = zip(*sorted(SCREAMING_SNAKE_CASE_ ) ) return {"language": languages, "translation": translations} def UpperCamelCase( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value('string' ) ), "translation": Sequence(Value('string' ) ), }
42
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler A_ = 16 A_ = 32 def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = 16 ,__UpperCamelCase = "bert-base-cased" ) -> List[Any]: lowerCamelCase_ = AutoTokenizer.from_pretrained(__UpperCamelCase ) lowerCamelCase_ = load_dataset('glue' ,'mrpc' ) def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) lowerCamelCase_ = tokenizer(examples['sentence1'] ,examples['sentence2'] ,truncation=__UpperCamelCase ,max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowerCamelCase_ = datasets.map( __UpperCamelCase ,batched=__UpperCamelCase ,remove_columns=['idx', 'sentence1', 'sentence2'] ,load_from_cache_file=__UpperCamelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCamelCase_ = tokenized_datasets.rename_column('label' ,'labels' ) 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. lowerCamelCase_ = DataLoader( tokenized_datasets['train'] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) lowerCamelCase_ = DataLoader( tokenized_datasets['validation'] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Union[str, Any]: model.eval() lowerCamelCase_ = 0 for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times lowerCamelCase_ ,lowerCamelCase_ = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__UpperCamelCase ) - 1: lowerCamelCase_ = predictions[: len(eval_dataloader.dataset ) - samples_seen] lowerCamelCase_ = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__UpperCamelCase ,references=__UpperCamelCase ,) lowerCamelCase_ = metric.compute() return eval_metric["accuracy"] def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> List[str]: # Initialize accelerator lowerCamelCase_ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCamelCase_ = config['lr'] lowerCamelCase_ = int(config['num_epochs'] ) lowerCamelCase_ = int(config['seed'] ) lowerCamelCase_ = int(config['batch_size'] ) lowerCamelCase_ = args.model_name_or_path set_seed(__UpperCamelCase ) lowerCamelCase_ ,lowerCamelCase_ = get_dataloaders(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCamelCase_ = AutoModelForSequenceClassification.from_pretrained(__UpperCamelCase ,return_dict=__UpperCamelCase ) # Instantiate optimizer lowerCamelCase_ = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowerCamelCase_ = optimizer_cls(params=model.parameters() ,lr=__UpperCamelCase ) if accelerator.state.deepspeed_plugin is not None: lowerCamelCase_ = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: lowerCamelCase_ = 1 lowerCamelCase_ = (len(__UpperCamelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowerCamelCase_ = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase ,num_warmup_steps=0 ,num_training_steps=__UpperCamelCase ,) else: lowerCamelCase_ = DummyScheduler(__UpperCamelCase ,total_num_steps=__UpperCamelCase ,warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = accelerator.prepare( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # We need to keep track of how many total steps we have iterated over lowerCamelCase_ = 0 # We also need to keep track of the stating epoch so files are named properly lowerCamelCase_ = 0 lowerCamelCase_ = evaluate.load('glue' ,'mrpc' ) lowerCamelCase_ = num_epochs if args.partial_train_epoch is not None: lowerCamelCase_ = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) lowerCamelCase_ = args.resume_from_checkpoint.split('epoch_' )[1] lowerCamelCase_ = '' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break lowerCamelCase_ = int(__UpperCamelCase ) + 1 lowerCamelCase_ = evaluation_loop(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) accelerator.print('resumed checkpoint performance:' ,__UpperCamelCase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:' ,lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:' ,optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir ,f'''state_{starting_epoch-1}.json''' ) ,'r' ) as f: lowerCamelCase_ = json.load(__UpperCamelCase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model lowerCamelCase_ = {} for epoch in range(__UpperCamelCase ,__UpperCamelCase ): model.train() for step, batch in enumerate(__UpperCamelCase ): lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.loss lowerCamelCase_ = loss / gradient_accumulation_steps accelerator.backward(__UpperCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 lowerCamelCase_ = f'''epoch_{epoch}''' lowerCamelCase_ = os.path.join(args.output_dir ,__UpperCamelCase ) accelerator.save_state(__UpperCamelCase ) lowerCamelCase_ = evaluation_loop(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) lowerCamelCase_ = accuracy lowerCamelCase_ = lr_scheduler.get_lr()[0] lowerCamelCase_ = optimizer.param_groups[0]['lr'] lowerCamelCase_ = epoch lowerCamelCase_ = overall_step accelerator.print(f'''epoch {epoch}:''' ,__UpperCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,f'''state_{epoch}.json''' ) ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( ) -> str: lowerCamelCase_ = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' ,type=__UpperCamelCase ,default='bert-base-cased' ,help='Path to pretrained model or model identifier from huggingface.co/models.' ,required=__UpperCamelCase ,) parser.add_argument( '--output_dir' ,type=__UpperCamelCase ,default='.' ,help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' ,) parser.add_argument( '--resume_from_checkpoint' ,type=__UpperCamelCase ,default=__UpperCamelCase ,help='If the training should continue from a checkpoint folder.' ,) parser.add_argument( '--partial_train_epoch' ,type=__UpperCamelCase ,default=__UpperCamelCase ,help='If passed, the training will stop after this number of epochs.' ,) parser.add_argument( '--num_epochs' ,type=__UpperCamelCase ,default=2 ,help='Number of train epochs.' ,) lowerCamelCase_ = parser.parse_args() lowerCamelCase_ = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(__UpperCamelCase ,__UpperCamelCase ) if __name__ == "__main__": main()
42
1
'''simple docstring''' from math import isclose, sqrt def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> tuple[float, float, float]: lowerCamelCase_ = point_y / 4 / point_x lowerCamelCase_ = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) lowerCamelCase_ = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) lowerCamelCase_ = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 lowerCamelCase_ = outgoing_gradient**2 + 4 lowerCamelCase_ = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) lowerCamelCase_ = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 lowerCamelCase_ = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) lowerCamelCase_ = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point lowerCamelCase_ = x_minus if isclose(__UpperCamelCase ,__UpperCamelCase ) else x_plus lowerCamelCase_ = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _UpperCamelCase ( __UpperCamelCase = 1.4 ,__UpperCamelCase = -9.6 ) -> int: lowerCamelCase_ = 0 lowerCamelCase_ = first_x_coord lowerCamelCase_ = first_y_coord lowerCamelCase_ = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = next_point(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
42
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> np.ndarray: # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: lowerCamelCase_ = ksize + 1 lowerCamelCase_ = np.zeros((ksize, ksize) ,dtype=np.floataa ) # each value for y in range(__UpperCamelCase ): for x in range(__UpperCamelCase ): # distance from center lowerCamelCase_ = x - ksize // 2 lowerCamelCase_ = y - ksize // 2 # degree to radiant lowerCamelCase_ = theta / 1_80 * np.pi lowerCamelCase_ = np.cos(_theta ) lowerCamelCase_ = np.sin(_theta ) # get kernel x lowerCamelCase_ = cos_theta * px + sin_theta * py # get kernel y lowerCamelCase_ = -sin_theta * px + cos_theta * py # fill kernel lowerCamelCase_ = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image A_ = imread("../image_data/lena.jpg") # turn image in gray scale value A_ = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges A_ = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: A_ = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) A_ = out / out.max() * 255 A_ = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
42
1
'''simple docstring''' from collections.abc import Sequence from queue import Queue class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ) -> str: '''simple docstring''' lowerCamelCase_ = start lowerCamelCase_ = end lowerCamelCase_ = val lowerCamelCase_ = (start + end) // 2 lowerCamelCase_ = left lowerCamelCase_ = right def __repr__( self ) -> Tuple: '''simple docstring''' return f'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' lowerCamelCase_ = collection lowerCamelCase_ = function if self.collection: lowerCamelCase_ = self._build_tree(0 , len(SCREAMING_SNAKE_CASE_ ) - 1 ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' self._update_tree(self.root , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' return self._query_range(self.root , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' if start == end: return SegmentTreeNode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.collection[start] ) lowerCamelCase_ = (start + end) // 2 lowerCamelCase_ = self._build_tree(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self._build_tree(mid + 1 , SCREAMING_SNAKE_CASE_ ) return SegmentTreeNode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.fn(left.val , right.val ) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' if node.start == i and node.end == i: lowerCamelCase_ = val return if i <= node.mid: self._update_tree(node.left , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: self._update_tree(node.right , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.fn(node.left.val , node.right.val ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , SCREAMING_SNAKE_CASE_ , node.mid ) , self._query_range(node.right , node.mid + 1 , SCREAMING_SNAKE_CASE_ ) , ) else: # range in right child tree return self._query_range(node.right , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> int: '''simple docstring''' if self.root is not None: lowerCamelCase_ = Queue() queue.put(self.root ) while not queue.empty(): lowerCamelCase_ = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) A_ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
42
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['transformers', 'torch', 'note_seq'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['transformers', 'torch', 'note_seq'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['transformers', 'torch', 'note_seq'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' requires_backends(cls , ['transformers', 'torch', 'note_seq'] )
42
1
'''simple docstring''' import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('foo.json',)] ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = AutoConfig.from_pretrained('gpt2' ) lowerCamelCase_ = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = GenerationConfig() lowerCamelCase_ = { 'max_new_tokens': 1024, 'foo': 'bar', } lowerCamelCase_ = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = generation_config.update(**SCREAMING_SNAKE_CASE_ ) # update_kwargs was not modified (no side effects) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(SCREAMING_SNAKE_CASE_ , {'foo': 'bar'} ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = GenerationConfig() lowerCamelCase_ = 'bar' with tempfile.TemporaryDirectory('test-generation-config' ) as tmp_dir: generation_config.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , 'bar' ) lowerCamelCase_ = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) assert not hasattr(SCREAMING_SNAKE_CASE_ , 'foo' ) # no new kwargs should be initialized if from config def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(default_config.num_beams , 1 ) lowerCamelCase_ = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @classmethod def UpperCamelCase( cls ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def UpperCamelCase( cls ) -> Tuple: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='test-generation-config' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-generation-config-org' ) except HTTPError: pass def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('test-generation-config' , use_auth_token=self._token ) lowerCamelCase_ = GenerationConfig.from_pretrained(f'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='test-generation-config' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='test-generation-config' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) lowerCamelCase_ = GenerationConfig.from_pretrained(f'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('valid_org/test-generation-config-org' , use_auth_token=self._token ) lowerCamelCase_ = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-generation-config-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='valid_org/test-generation-config-org' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) lowerCamelCase_ = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
42
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def UpperCamelCase( self ) -> int: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , ) return model @property def UpperCamelCase( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) lowerCamelCase_ = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) lowerCamelCase_ = DDPMScheduler() lowerCamelCase_ = AudioDiffusionPipeline(vqvae=SCREAMING_SNAKE_CASE_ , unet=self.dummy_unet , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , steps=4 ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = output.images[0] lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , steps=4 , return_dict=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 lowerCamelCase_ = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) lowerCamelCase_ = DDIMScheduler() lowerCamelCase_ = self.dummy_vqvae_and_unet lowerCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) np.random.seed(0 ) lowerCamelCase_ = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(raw_audio=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , start_step=5 , steps=10 ) lowerCamelCase_ = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 lowerCamelCase_ = self.dummy_unet_condition lowerCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=SCREAMING_SNAKE_CASE_ , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) np.random.seed(0 ) lowerCamelCase_ = torch.rand((1, 1, 10) ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , encoding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.images[0] lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = torch_device lowerCamelCase_ = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
42
1
'''simple docstring''' import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL A_ = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=False ,) -> Any: output_path.parent.mkdir(parents=__UpperCamelCase ,exist_ok=__UpperCamelCase ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( __UpperCamelCase ,__UpperCamelCase ,f=output_path.as_posix() ,input_names=__UpperCamelCase ,output_names=__UpperCamelCase ,dynamic_axes=__UpperCamelCase ,do_constant_folding=__UpperCamelCase ,use_external_data_format=__UpperCamelCase ,enable_onnx_checker=__UpperCamelCase ,opset_version=__UpperCamelCase ,) else: export( __UpperCamelCase ,__UpperCamelCase ,f=output_path.as_posix() ,input_names=__UpperCamelCase ,output_names=__UpperCamelCase ,dynamic_axes=__UpperCamelCase ,do_constant_folding=__UpperCamelCase ,opset_version=__UpperCamelCase ,) @torch.no_grad() def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase = False ) -> Dict: lowerCamelCase_ = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): lowerCamelCase_ = 'cuda' elif fpaa and not torch.cuda.is_available(): raise ValueError('`float16` model export is only supported on GPUs with CUDA' ) else: lowerCamelCase_ = 'cpu' lowerCamelCase_ = Path(__UpperCamelCase ) # VAE DECODER lowerCamelCase_ = AutoencoderKL.from_pretrained(model_path + '/vae' ) lowerCamelCase_ = vae_decoder.config.latent_channels # forward only through the decoder part lowerCamelCase_ = vae_decoder.decode onnx_export( __UpperCamelCase ,model_args=( torch.randn(1 ,__UpperCamelCase ,25 ,25 ).to(device=__UpperCamelCase ,dtype=__UpperCamelCase ), False, ) ,output_path=output_path / 'vae_decoder' / 'model.onnx' ,ordered_input_names=['latent_sample', 'return_dict'] ,output_names=['sample'] ,dynamic_axes={ 'latent_sample': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'}, } ,opset=__UpperCamelCase ,) del vae_decoder if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument( "--model_path", type=str, required=True, help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).", ) parser.add_argument("--output_path", type=str, required=True, help="Path to the output model.") parser.add_argument( "--opset", default=14, type=int, help="The version of the ONNX operator set to use.", ) parser.add_argument("--fp16", action="store_true", default=False, help="Export the models in `float16` mode") A_ = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print("SD: Done: ONNX")
42
'''simple docstring''' import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _UpperCamelCase ( __UpperCamelCase = 8 ) -> str: lowerCamelCase_ = ascii_letters + digits + punctuation return "".join(secrets.choice(__UpperCamelCase ) for _ in range(__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(__UpperCamelCase ) lowerCamelCase_ = i // 3 lowerCamelCase_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) lowerCamelCase_ = ( chars_incl + random(__UpperCamelCase ,quotient + remainder ) + random(__UpperCamelCase ,__UpperCamelCase ) + random(__UpperCamelCase ,__UpperCamelCase ) ) lowerCamelCase_ = list(__UpperCamelCase ) shuffle(__UpperCamelCase ) return "".join(__UpperCamelCase ) # random is a generalised function for letters, characters and numbers def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: return "".join(secrets.choice(__UpperCamelCase ) for _ in range(__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Optional[int]: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Tuple: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = 8 ) -> bool: if len(__UpperCamelCase ) < min_length: # Your Password must be at least 8 characters long return False lowerCamelCase_ = any(char in ascii_uppercase for char in password ) lowerCamelCase_ = any(char in ascii_lowercase for char in password ) lowerCamelCase_ = any(char in digits for char in password ) lowerCamelCase_ = 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 _UpperCamelCase ( ) -> Optional[int]: lowerCamelCase_ = int(input('Please indicate the max length of your password: ' ).strip() ) lowerCamelCase_ = input( 'Please indicate the characters that must be in your password: ' ).strip() print('Password generated:' ,password_generator(__UpperCamelCase ) ) print( 'Alternative Password generated:' ,alternative_password_generator(__UpperCamelCase ,__UpperCamelCase ) ,) print('[If you are thinking of using this passsword, You better save it.]' ) if __name__ == "__main__": main()
42
1
'''simple docstring''' from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> float: '''simple docstring''' return 0.0 def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> tuple[int | float, int | float]: lowerCamelCase_ = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) lowerCamelCase_ = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: lowerCamelCase_ = 5_12 lowerCamelCase_ = [1] + [0] * (size - 1) lowerCamelCase_ = [filter_type.process(__UpperCamelCase ) for item in inputs] lowerCamelCase_ = [0] * (samplerate - size) # zero-padding outputs += filler lowerCamelCase_ = np.abs(np.fft.fft(__UpperCamelCase ) ) lowerCamelCase_ = 20 * np.logaa(__UpperCamelCase ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 ,samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) # Display within reasonable bounds lowerCamelCase_ = get_bounds(__UpperCamelCase ,__UpperCamelCase ) plt.ylim(max([-80, bounds[0]] ) ,min([80, bounds[1]] ) ) plt.ylabel('Gain (dB)' ) plt.plot(__UpperCamelCase ) plt.show() def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: lowerCamelCase_ = 5_12 lowerCamelCase_ = [1] + [0] * (size - 1) lowerCamelCase_ = [filter_type.process(__UpperCamelCase ) for item in inputs] lowerCamelCase_ = [0] * (samplerate - size) # zero-padding outputs += filler lowerCamelCase_ = np.angle(np.fft.fft(__UpperCamelCase ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 ,samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) plt.ylim(-2 * pi ,2 * pi ) plt.ylabel('Phase shift (Radians)' ) plt.plot(np.unwrap(__UpperCamelCase ,-2 * pi ) ) plt.show()
42
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 lowerCamelCase_ = test_metrics @require_cpu def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def UpperCamelCase( self ) -> Tuple: '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def UpperCamelCase( self ) -> Any: '''simple docstring''' self.test_metrics.main() @require_multi_gpu def UpperCamelCase( self ) -> Any: '''simple docstring''' print(f'''Found {torch.cuda.device_count()} devices.''' ) lowerCamelCase_ = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() )
42
1
'''simple docstring''' import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = FlaxXLMRobertaModel.from_pretrained('xlm-roberta-base' ) lowerCamelCase_ = AutoTokenizer.from_pretrained('xlm-roberta-base' ) lowerCamelCase_ = 'The dog is cute and lives in the garden house' lowerCamelCase_ = jnp.array([tokenizer.encode(SCREAMING_SNAKE_CASE_ )] ) lowerCamelCase_ = (1, 12, 768) # batch_size, sequence_length, embedding_vector_dim lowerCamelCase_ = jnp.array( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )['last_hidden_state'] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) )
42
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True) os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True) os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: if hor == 1_28: lowerCamelCase_ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') lowerCamelCase_ = (32, 1_28, 2_56) lowerCamelCase_ = ('UpResnetBlock1D', 'UpResnetBlock1D') elif hor == 32: lowerCamelCase_ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') lowerCamelCase_ = (32, 64, 1_28, 2_56) lowerCamelCase_ = ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D') lowerCamelCase_ = torch.load(f'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' ) lowerCamelCase_ = model.state_dict() lowerCamelCase_ = { 'down_block_types': down_block_types, 'block_out_channels': block_out_channels, 'up_block_types': up_block_types, 'layers_per_block': 1, 'use_timestep_embedding': True, 'out_block_type': 'OutConv1DBlock', 'norm_num_groups': 8, 'downsample_each_block': False, 'in_channels': 14, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'flip_sin_to_cos': False, 'freq_shift': 1, 'sample_size': 6_55_36, 'mid_block_type': 'MidResTemporalBlock1D', 'act_fn': 'mish', } lowerCamelCase_ = UNetaDModel(**__UpperCamelCase ) print(f'''length of state dict: {len(state_dict.keys() )}''' ) print(f'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) lowerCamelCase_ = dict(zip(model.state_dict().keys() ,hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): lowerCamelCase_ = state_dict.pop(__UpperCamelCase ) hf_value_function.load_state_dict(__UpperCamelCase ) torch.save(hf_value_function.state_dict() ,f'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' ) with open(f'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( ) -> Tuple: lowerCamelCase_ = { 'in_channels': 14, 'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'), 'up_block_types': (), 'out_block_type': 'ValueFunction', 'mid_block_type': 'ValueFunctionMidBlock1D', 'block_out_channels': (32, 64, 1_28, 2_56), 'layers_per_block': 1, 'downsample_each_block': True, 'sample_size': 6_55_36, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'use_timestep_embedding': True, 'flip_sin_to_cos': False, 'freq_shift': 1, 'norm_num_groups': 8, 'act_fn': 'mish', } lowerCamelCase_ = torch.load('/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch' ) lowerCamelCase_ = model lowerCamelCase_ = UNetaDModel(**__UpperCamelCase ) print(f'''length of state dict: {len(state_dict.keys() )}''' ) print(f'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) lowerCamelCase_ = dict(zip(state_dict.keys() ,hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): lowerCamelCase_ = state_dict.pop(__UpperCamelCase ) hf_value_function.load_state_dict(__UpperCamelCase ) torch.save(hf_value_function.state_dict() ,'hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin' ) with open('hub/hopper-medium-v2/value_function/config.json' ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) if __name__ == "__main__": unet(32) # unet(128) value_function()
42
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ = { "configuration_luke": ["LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP", "LukeConfig"], "tokenization_luke": ["LukeTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "LUKE_PRETRAINED_MODEL_ARCHIVE_LIST", "LukeForEntityClassification", "LukeForEntityPairClassification", "LukeForEntitySpanClassification", "LukeForMultipleChoice", "LukeForQuestionAnswering", "LukeForSequenceClassification", "LukeForTokenClassification", "LukeForMaskedLM", "LukeModel", "LukePreTrainedModel", ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
42
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, 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 A_ = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A_ = 250_004 A_ = 250_020 @require_sentencepiece @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = MBartTokenizer SCREAMING_SNAKE_CASE_ = MBartTokenizerFast SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase_ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase_ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def UpperCamelCase( self ) -> int: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase_ = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCamelCase_ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) lowerCamelCase_ = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=True lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=False lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'facebook/mbart-large-en-ro' SCREAMING_SNAKE_CASE_ = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] SCREAMING_SNAKE_CASE_ = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] SCREAMING_SNAKE_CASE_ = [82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2, EN_CODE] @classmethod def UpperCamelCase( cls ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) lowerCamelCase_ = 1 return cls def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 250020 ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' self.assertIn(SCREAMING_SNAKE_CASE_ , self.tokenizer.all_special_ids ) lowerCamelCase_ = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] lowerCamelCase_ = self.tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 10 lowerCamelCase_ = self.tokenizer(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [250026, 250001] ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = MBartTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) lowerCamelCase_ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=3 , return_tensors='pt' ) lowerCamelCase_ = self.tokenizer( text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=10 , return_tensors='pt' ) lowerCamelCase_ = targets['input_ids'] lowerCamelCase_ = shift_tokens_right(SCREAMING_SNAKE_CASE_ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ) , { # A, test, EOS, en_XX 'input_ids': [[62, 3034, 2, 250004]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 250001, } , )
42
1
'''simple docstring''' 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, ) A_ = logging.get_logger(__name__) # pylint: disable=invalid-name A_ = "\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\")\n >>> pipe_prior.to(\"cuda\")\n >>> prompt = \"red cat, 4k photo\"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> zero_image_emb = out.negative_image_embeds\n >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\")\n >>> pipe.to(\"cuda\")\n >>> image = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=50,\n ... ).images\n >>> image[0].save(\"cat.png\")\n ```\n" def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=8 ) -> List[Any]: lowerCamelCase_ = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 lowerCamelCase_ = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: '''simple docstring''' super().__init__() self.register_modules( unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , movq=SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' if latents is None: lowerCamelCase_ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) lowerCamelCase_ = latents.to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = latents * scheduler.init_noise_sigma return latents def UpperCamelCase( self , SCREAMING_SNAKE_CASE_=0 ) -> Optional[int]: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) lowerCamelCase_ = torch.device(f'''cuda:{gpu_id}''' ) lowerCamelCase_ = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_=0 ) -> Optional[Any]: '''simple docstring''' 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.' ) lowerCamelCase_ = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=SCREAMING_SNAKE_CASE_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) lowerCamelCase_ = None for cpu_offloaded_model in [self.unet, self.movq]: lowerCamelCase_ ,lowerCamelCase_ = cpu_offload_with_hook(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prev_module_hook=SCREAMING_SNAKE_CASE_ ) # We'll offload the last model manually. lowerCamelCase_ = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCamelCase( self ) -> List[str]: '''simple docstring''' if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(SCREAMING_SNAKE_CASE_ , '_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(SCREAMING_SNAKE_CASE_ ) def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = 4.0 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ) -> List[str]: '''simple docstring''' lowerCamelCase_ = self._execution_device lowerCamelCase_ = guidance_scale > 1.0 if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) lowerCamelCase_ = image_embeds.shape[0] * num_images_per_prompt if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) if do_classifier_free_guidance: lowerCamelCase_ = image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) lowerCamelCase_ = negative_image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) lowerCamelCase_ = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=SCREAMING_SNAKE_CASE_ ) self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.scheduler.timesteps lowerCamelCase_ = self.unet.config.in_channels lowerCamelCase_ ,lowerCamelCase_ = downscale_height_and_width(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.movq_scale_factor ) # create initial latent lowerCamelCase_ = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance lowerCamelCase_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCamelCase_ = {'image_embeds': image_embeds} lowerCamelCase_ = self.unet( sample=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , added_cond_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] if do_classifier_free_guidance: lowerCamelCase_ ,lowerCamelCase_ = noise_pred.split(latents.shape[1] , dim=1 ) lowerCamelCase_ ,lowerCamelCase_ = noise_pred.chunk(2 ) lowerCamelCase_ ,lowerCamelCase_ = variance_pred.chunk(2 ) lowerCamelCase_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) lowerCamelCase_ = 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"] ): lowerCamelCase_ ,lowerCamelCase_ = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ = self.scheduler.step( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , )[0] # post-processing lowerCamelCase_ = self.movq.decode(SCREAMING_SNAKE_CASE_ , force_not_quantize=SCREAMING_SNAKE_CASE_ )['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"]: lowerCamelCase_ = image * 0.5 + 0.5 lowerCamelCase_ = image.clamp(0 , 1 ) lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": lowerCamelCase_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
42
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = 'ylacombe/bark-small' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = 'en_speaker_1' lowerCamelCase_ = 'This is a test string' lowerCamelCase_ = 'speaker_embeddings_path.json' lowerCamelCase_ = 'speaker_embeddings' def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase_ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase_ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCamelCase_ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='(BOS)' , eos_token='(EOS)' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase_ = 35 lowerCamelCase_ = 2 lowerCamelCase_ = 8 lowerCamelCase_ = { 'semantic_prompt': np.ones(SCREAMING_SNAKE_CASE_ ), 'coarse_prompt': np.ones((nb_codebooks_coarse, seq_len) ), 'fine_prompt': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() ) # test loading voice preset from npz file lowerCamelCase_ = os.path.join(self.tmpdirname , 'file.npz' ) np.savez(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() ) # test loading voice preset from the hub lowerCamelCase_ = processor(text=self.input_string , voice_preset=self.voice_preset ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = processor(text=self.input_string ) lowerCamelCase_ = tokenizer( self.input_string , padding='max_length' , max_length=256 , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
42
1
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = [10, 20, 30, 40, 50, 60] lowerCamelCase_ = [2, 4, 6, 8, 10, 12] lowerCamelCase_ = 100 self.assertEqual(kp.calc_profit(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , 210 ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' self.assertRaisesRegex(SCREAMING_SNAKE_CASE_ , 'max_weight must greater than zero.' ) def UpperCamelCase( self ) -> str: '''simple docstring''' self.assertRaisesRegex(SCREAMING_SNAKE_CASE_ , 'Weight can not be negative.' ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.assertRaisesRegex(SCREAMING_SNAKE_CASE_ , 'Profit can not be negative.' ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' self.assertRaisesRegex(SCREAMING_SNAKE_CASE_ , 'max_weight must greater than zero.' ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
42
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} A_ = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } A_ = { "allenai/longformer-base-4096": 4_096, "allenai/longformer-large-4096": 4_096, "allenai/longformer-large-4096-finetuned-triviaqa": 4_096, "allenai/longformer-base-4096-extra.pos.embd.only": 4_096, "allenai/longformer-large-4096-extra.pos.embd.only": 4_096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _UpperCamelCase ( ) -> Any: lowerCamelCase_ = ( list(range(ord('!' ) ,ord('~' ) + 1 ) ) + list(range(ord('¡' ) ,ord('¬' ) + 1 ) ) + list(range(ord('®' ) ,ord('ÿ' ) + 1 ) ) ) lowerCamelCase_ = bs[:] lowerCamelCase_ = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 lowerCamelCase_ = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase ,__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: lowerCamelCase_ = set() lowerCamelCase_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCamelCase_ = char return pairs class UpperCAmelCase ( UpperCAmelCase__ ): '''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 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="replace" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else bos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else eos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else sep_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else cls_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else unk_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( errors=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as vocab_handle: lowerCamelCase_ = json.load(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {v: k for k, v in self.encoder.items()} lowerCamelCase_ = errors # how to handle errors in decoding lowerCamelCase_ = bytes_to_unicode() lowerCamelCase_ = {v: k for k, v in self.byte_encoder.items()} with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as merges_handle: lowerCamelCase_ = merges_handle.read().split('\n' )[1:-1] lowerCamelCase_ = [tuple(merge.split() ) for merge in bpe_merges] lowerCamelCase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowerCamelCase_ = {} lowerCamelCase_ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowerCamelCase_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' return len(self.encoder ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' if token in self.cache: return self.cache[token] lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) if not pairs: return token while True: lowerCamelCase_ = min(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break lowerCamelCase_ ,lowerCamelCase_ = bigram lowerCamelCase_ = [] lowerCamelCase_ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): try: lowerCamelCase_ = word.index(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCamelCase_ = j if word[i] == first and i < len(SCREAMING_SNAKE_CASE_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = new_word if len(SCREAMING_SNAKE_CASE_ ) == 1: break else: lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = ' '.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = word return word def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' lowerCamelCase_ = [] for token in re.findall(self.pat , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(SCREAMING_SNAKE_CASE_ ).split(' ' ) ) return bpe_tokens def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' return self.encoder.get(SCREAMING_SNAKE_CASE_ , self.encoder.get(self.unk_token ) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' return self.decoder.get(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = ''.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) + '\n' ) lowerCamelCase_ = 0 with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ' Please check that the tokenizer is not corrupted!' ) lowerCamelCase_ = token_index writer.write(' '.join(SCREAMING_SNAKE_CASE_ ) + '\n' ) index += 1 return vocab_file, merge_file def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] lowerCamelCase_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' lowerCamelCase_ = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(SCREAMING_SNAKE_CASE_ ) > 0 and not text[0].isspace()): lowerCamelCase_ = ' ' + text return (text, kwargs)
42
1
'''simple docstring''' import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser A_ = logging.getLogger(__name__) torch.set_grad_enabled(False) A_ = "cuda" if torch.cuda.is_available() else "cpu" def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase=1_00 ,__UpperCamelCase=" " ) -> List[str]: lowerCamelCase_ = text.split(__UpperCamelCase ) return [character.join(text[i : i + n] ).strip() for i in range(0 ,len(__UpperCamelCase ) ,__UpperCamelCase )] def _UpperCamelCase ( __UpperCamelCase ) -> dict: lowerCamelCase_ ,lowerCamelCase_ = [], [] for title, text in zip(documents['title'] ,documents['text'] ): if text is not None: for passage in split_text(__UpperCamelCase ): titles.append(title if title is not None else '' ) texts.append(__UpperCamelCase ) return {"title": titles, "text": texts} def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> dict: lowerCamelCase_ = ctx_tokenizer( documents['title'] ,documents['text'] ,truncation=__UpperCamelCase ,padding='longest' ,return_tensors='pt' )['input_ids'] lowerCamelCase_ = ctx_encoder(input_ids.to(device=__UpperCamelCase ) ,return_dict=__UpperCamelCase ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,) -> Union[str, Any]: ###################################### logger.info('Step 1 - Create the dataset' ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way lowerCamelCase_ = load_dataset( 'csv' ,data_files=[rag_example_args.csv_path] ,split='train' ,delimiter='\t' ,column_names=['title', 'text'] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words lowerCamelCase_ = dataset.map(__UpperCamelCase ,batched=__UpperCamelCase ,num_proc=processing_args.num_proc ) # And compute the embeddings lowerCamelCase_ = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=__UpperCamelCase ) lowerCamelCase_ = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) lowerCamelCase_ = Features( {'text': Value('string' ), 'title': Value('string' ), 'embeddings': Sequence(Value('float32' ) )} ) # optional, save as float32 instead of float64 to save space lowerCamelCase_ = dataset.map( partial(__UpperCamelCase ,ctx_encoder=__UpperCamelCase ,ctx_tokenizer=__UpperCamelCase ) ,batched=__UpperCamelCase ,batch_size=processing_args.batch_size ,features=__UpperCamelCase ,) # And finally save your dataset lowerCamelCase_ = os.path.join(rag_example_args.output_dir ,'my_knowledge_dataset' ) dataset.save_to_disk(__UpperCamelCase ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info('Step 2 - Index the dataset' ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search lowerCamelCase_ = faiss.IndexHNSWFlat(index_hnsw_args.d ,index_hnsw_args.m ,faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index('embeddings' ,custom_index=__UpperCamelCase ) # And save the index lowerCamelCase_ = os.path.join(rag_example_args.output_dir ,'my_knowledge_dataset_hnsw_index.faiss' ) dataset.get_index('embeddings' ).save(__UpperCamelCase ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE_ = field( default=str(Path(UpperCAmelCase__ ).parent / 'test_run' / 'dummy-kb' / 'my_knowledge_dataset.csv' ) , metadata={'help': 'Path to a tab-separated csv file with columns \'title\' and \'text\''} , ) SCREAMING_SNAKE_CASE_ = field( default=UpperCAmelCase__ , metadata={'help': 'Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'.'} , ) SCREAMING_SNAKE_CASE_ = field( default='facebook/rag-sequence-nq' , metadata={'help': 'The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\''} , ) SCREAMING_SNAKE_CASE_ = field( default='facebook/dpr-ctx_encoder-multiset-base' , metadata={ 'help': ( 'The DPR context encoder model to use. Either \'facebook/dpr-ctx_encoder-single-nq-base\' or' ' \'facebook/dpr-ctx_encoder-multiset-base\'' ) } , ) SCREAMING_SNAKE_CASE_ = field( default=str(Path(UpperCAmelCase__ ).parent / 'test_run' / 'dummy-kb' ) , metadata={'help': 'Path to a directory where the dataset passages and the index will be saved'} , ) @dataclass class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE_ = field( default=UpperCAmelCase__ , metadata={ 'help': 'The number of processes to use to split the documents into passages. Default is single process.' } , ) SCREAMING_SNAKE_CASE_ = field( default=16 , metadata={ 'help': 'The batch size to use when computing the passages embeddings using the DPR context encoder.' } , ) @dataclass class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE_ = field( default=7_68 , metadata={'help': 'The dimension of the embeddings to pass to the HNSW Faiss index.'} , ) SCREAMING_SNAKE_CASE_ = field( default=1_28 , metadata={ 'help': ( 'The number of bi-directional links created for every new element during the HNSW index construction.' ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) A_ = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) A_ , A_ , A_ = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: A_ = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
42
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} A_ = { "vocab_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt" ), "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt", "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt", "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt", "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt", }, "tokenizer_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json" ), "google/realm-orqa-nq-openqa": ( "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-nq-reader": ( "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-openqa": ( "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-reader": ( "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json" ), }, } A_ = { "google/realm-cc-news-pretrained-embedder": 512, "google/realm-cc-news-pretrained-encoder": 512, "google/realm-cc-news-pretrained-scorer": 512, "google/realm-cc-news-pretrained-openqa": 512, "google/realm-orqa-nq-openqa": 512, "google/realm-orqa-nq-reader": 512, "google/realm-orqa-wq-openqa": 512, "google/realm-orqa-wq-reader": 512, } A_ = { "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-reader": {"do_lower_case": True}, "google/realm-orqa-wq-openqa": {"do_lower_case": True}, "google/realm-orqa-wq-reader": {"do_lower_case": True}, } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ = RealmTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="[UNK]" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="[PAD]" , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[MASK]" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> List[Any]: '''simple docstring''' super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , do_lower_case=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , SCREAMING_SNAKE_CASE_ ) != do_lower_case or normalizer_state.get('strip_accents' , SCREAMING_SNAKE_CASE_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , SCREAMING_SNAKE_CASE_ ) != tokenize_chinese_chars ): lowerCamelCase_ = getattr(SCREAMING_SNAKE_CASE_ , normalizer_state.pop('type' ) ) lowerCamelCase_ = do_lower_case lowerCamelCase_ = strip_accents lowerCamelCase_ = tokenize_chinese_chars lowerCamelCase_ = normalizer_class(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = do_lower_case def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = PaddingStrategy.MAX_LENGTH lowerCamelCase_ = text lowerCamelCase_ = kwargs.pop('text_pair' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = kwargs.pop('return_tensors' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'input_ids': [], 'attention_mask': [], 'token_type_ids': [], } for idx, candidate_text in enumerate(SCREAMING_SNAKE_CASE_ ): if batch_text_pair is not None: lowerCamelCase_ = batch_text_pair[idx] else: lowerCamelCase_ = None lowerCamelCase_ = super().__call__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = encoded_candidates.get('input_ids' ) lowerCamelCase_ = encoded_candidates.get('attention_mask' ) lowerCamelCase_ = encoded_candidates.get('token_type_ids' ) if encoded_input_ids is not None: output_data["input_ids"].append(SCREAMING_SNAKE_CASE_ ) if encoded_attention_mask is not None: output_data["attention_mask"].append(SCREAMING_SNAKE_CASE_ ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {key: item for key, item in output_data.items() if len(SCREAMING_SNAKE_CASE_ ) != 0} return BatchEncoding(SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' lowerCamelCase_ = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
42
1
'''simple docstring''' import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = AudioLDMPipeline SCREAMING_SNAKE_CASE_ = TEXT_TO_AUDIO_PARAMS SCREAMING_SNAKE_CASE_ = TEXT_TO_AUDIO_BATCH_PARAMS SCREAMING_SNAKE_CASE_ = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=(32, 64) , class_embed_type='simple_projection' , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) lowerCamelCase_ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) lowerCamelCase_ = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) lowerCamelCase_ = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = RobertaTokenizer.from_pretrained('hf-internal-testing/tiny-random-roberta' , model_max_length=77 ) lowerCamelCase_ = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=16000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'vocoder': vocoder, } return components def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ) -> Optional[Any]: '''simple docstring''' if str(SCREAMING_SNAKE_CASE_ ).startswith('mps' ): lowerCamelCase_ = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'prompt': 'A hammer hitting a wooden surface', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, } return inputs def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 lowerCamelCase_ = audio[:10] lowerCamelCase_ = np.array( [-0.0_050, 0.0_050, -0.0_060, 0.0_033, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_033] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 3 * [inputs['prompt']] # forward lowerCamelCase_ = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 3 * [inputs.pop('prompt' )] lowerCamelCase_ = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='pt' , ) lowerCamelCase_ = text_inputs['input_ids'].to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state lowerCamelCase_ = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) lowerCamelCase_ = prompt_embeds # forward lowerCamelCase_ = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 3 * ['this is a negative prompt'] lowerCamelCase_ = negative_prompt lowerCamelCase_ = 3 * [inputs['prompt']] # forward lowerCamelCase_ = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 3 * [inputs.pop('prompt' )] lowerCamelCase_ = [] for p in [prompt, negative_prompt]: lowerCamelCase_ = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='pt' , ) lowerCamelCase_ = text_inputs['input_ids'].to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = text_embeds.text_embeds # additional L_2 normalization over each hidden-state lowerCamelCase_ = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ ,lowerCamelCase_ = embeds # forward lowerCamelCase_ = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 'egg cracking' lowerCamelCase_ = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 lowerCamelCase_ = audio[:10] lowerCamelCase_ = np.array( [-0.0_051, 0.0_050, -0.0_060, 0.0_034, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_032] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 'A hammer hitting a wooden surface' # test num_waveforms_per_prompt=1 (default) lowerCamelCase_ = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts lowerCamelCase_ = 2 lowerCamelCase_ = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt lowerCamelCase_ = 2 lowerCamelCase_ = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts lowerCamelCase_ = 2 lowerCamelCase_ = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.vocoder.config.sampling_rate lowerCamelCase_ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 lowerCamelCase_ = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = ['hey'] lowerCamelCase_ = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) lowerCamelCase_ = output.audios.shape assert audio_shape == (1, 256) lowerCamelCase_ = audioldm_pipe.vocoder.config config.model_in_dim *= 2 lowerCamelCase_ = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) lowerCamelCase_ = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def UpperCamelCase( self ) -> str: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ) -> int: '''simple docstring''' lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) lowerCamelCase_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'prompt': 'A hammer hitting a wooden surface', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 2.5, } return inputs def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = AudioLDMPipeline.from_pretrained('cvssp/audioldm' ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.get_inputs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 25 lowerCamelCase_ = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 81920 lowerCamelCase_ = audio[77230:77240] lowerCamelCase_ = np.array( [-0.4_884, -0.4_607, 0.0_023, 0.5_007, 0.5_896, 0.5_151, 0.3_813, -0.0_208, -0.3_687, -0.4_315] ) lowerCamelCase_ = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1E-2 def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = AudioLDMPipeline.from_pretrained('cvssp/audioldm' ) lowerCamelCase_ = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) lowerCamelCase_ = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.get_inputs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 81920 lowerCamelCase_ = audio[27780:27790] lowerCamelCase_ = np.array([-0.2_131, -0.0_873, -0.0_124, -0.0_189, 0.0_569, 0.1_373, 0.1_883, 0.2_886, 0.3_297, 0.2_212] ) lowerCamelCase_ = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3E-2
42
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __UpperCamelCase ) -> bool: lowerCamelCase_ = str(__UpperCamelCase ) return len(__UpperCamelCase ) == 9 and set(__UpperCamelCase ) == set('123456789' ) def _UpperCamelCase ( ) -> int | None: for base_num in range(99_99 ,49_99 ,-1 ): lowerCamelCase_ = 10_00_02 * base_num if is_9_pandigital(__UpperCamelCase ): return candidate for base_num in range(3_33 ,99 ,-1 ): lowerCamelCase_ = 1_00_20_03 * base_num if is_9_pandigital(__UpperCamelCase ): return candidate return None if __name__ == "__main__": print(f'''{solution() = }''')
42
1
'''simple docstring''' import os import pytest from transformers.dynamic_module_utils import get_imports A_ = "\nimport os\n" A_ = "\ndef foo():\n import os\n return False\n" A_ = "\ndef foo():\n def bar():\n if True:\n import os\n return False\n return bar()\n" A_ = "\nimport os\n\ntry:\n import bar\nexcept ImportError:\n raise ValueError()\n" A_ = "\nimport os\n\ndef foo():\n try:\n import bar\n except ImportError:\n raise ValueError()\n" A_ = "\nimport os\n\ntry:\n import bar\nexcept (ImportError, AttributeError):\n raise ValueError()\n" A_ = "\nimport os\n\ntry:\n import bar\nexcept ImportError as e:\n raise ValueError()\n" A_ = "\nimport os\n\ntry:\n import bar\nexcept:\n raise ValueError()\n" A_ = "\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n raise ValueError()\n" A_ = "\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n x = 1\n raise ValueError()\n" A_ = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize('case' ,__UpperCamelCase ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> List[Any]: lowerCamelCase_ = os.path.join(__UpperCamelCase ,'test_file.py' ) with open(__UpperCamelCase ,'w' ) as _tmp_file: _tmp_file.write(__UpperCamelCase ) lowerCamelCase_ = get_imports(__UpperCamelCase ) assert parsed_imports == ["os"]
42
'''simple docstring''' A_ = "Input must be a string of 8 numbers plus letter" A_ = "TRWAGMYFPDXBNJZSQVHLCKE" def _UpperCamelCase ( __UpperCamelCase ) -> bool: if not isinstance(__UpperCamelCase ,__UpperCamelCase ): lowerCamelCase_ = f'''Expected string as input, found {type(__UpperCamelCase ).__name__}''' raise TypeError(__UpperCamelCase ) lowerCamelCase_ = spanish_id.replace('-' ,'' ).upper() if len(__UpperCamelCase ) != 9: raise ValueError(__UpperCamelCase ) try: lowerCamelCase_ = int(spanish_id_clean[0:8] ) lowerCamelCase_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(__UpperCamelCase ) from ex if letter.isdigit(): raise ValueError(__UpperCamelCase ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
42
1
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ProphetNetTokenizer SCREAMING_SNAKE_CASE_ = False def UpperCamelCase( self ) -> int: '''simple docstring''' super().setUp() lowerCamelCase_ = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = 'UNwant\u00E9d,running' lowerCamelCase_ = 'unwanted, running' return input_text, output_text def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class(self.vocab_file ) lowerCamelCase_ = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [9, 6, 7, 12, 10, 11] ) def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) 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 ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] lowerCamelCase_ = {} for i, token in enumerate(SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = i lowerCamelCase_ = WordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE_ , 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'] ) @require_torch def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) lowerCamelCase_ = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] lowerCamelCase_ = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = list(batch.input_ids.numpy()[0] ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCamelCase( self ) -> Dict: '''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 ) -> Optional[int]: '''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 ) -> List[Any]: '''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(' ' ) ) @slow def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) lowerCamelCase_ = tokenizer.encode('sequence builders' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.encode('multi-sequence build' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
42
'''simple docstring''' import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = GPTSanJapaneseTokenizer SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = {'do_clean_text': False, 'add_prefix_space': False} def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' super().setUp() # fmt: off lowerCamelCase_ = ['こん', 'こんに', 'にちは', 'ばんは', '世界,㔺界', '、', '。', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on lowerCamelCase_ = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # 😀 lowerCamelCase_ = {'unk_token': '<unk>'} lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、世界。😀' return input_text, output_text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.get_input_output_texts(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ ) return text, ids def UpperCamelCase( self ) -> Tuple: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。 こんばんは、㔺界。' lowerCamelCase_ = ['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。'] lowerCamelCase_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids without special tokens lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids with special tokens lowerCamelCase_ = tokens + [tokenizer.unk_token] lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。' lowerCamelCase_ = 'こんにちは、、、、世界。こんばんは、、、、世界。' lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。こんばんは、世界。😀' lowerCamelCase_ = tokenizer.encode(prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode('' , prefix_text=prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = [1] + [0] * (len_prefix + len_text + 1) lowerCamelCase_ = [1] * (len_prefix + len_text + 1) + [0] lowerCamelCase_ = [1] + [1] * (len_prefix) + [0] * (len_text + 1) lowerCamelCase_ = tokenizer(prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = tokenizer.encode('あンいワ' ) lowerCamelCase_ = tokenizer.encode('' , prefix_text='あンいワ' ) lowerCamelCase_ = tokenizer.encode('いワ' , prefix_text='あン' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = [['武田信玄', 'は、'], ['織田信長', 'の配下の、']] lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) # fmt: off lowerCamelCase_ = [[35993, 8640, 25948, 35998, 30647, 35675, 35999, 35999], [35993, 10382, 9868, 35998, 30646, 9459, 30646, 35675]] lowerCamelCase_ = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] lowerCamelCase_ = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass
42
1
'''simple docstring''' import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def _UpperCamelCase ( __UpperCamelCase ) -> Optional[Any]: return EnvironmentCommand() class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' @staticmethod def UpperCamelCase( SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' lowerCamelCase_ = parser.add_parser('env' ) download_parser.set_defaults(func=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = huggingface_hub.__version__ lowerCamelCase_ = 'not installed' lowerCamelCase_ = 'NA' if is_torch_available(): import torch lowerCamelCase_ = torch.__version__ lowerCamelCase_ = torch.cuda.is_available() lowerCamelCase_ = 'not installed' if is_transformers_available(): import transformers lowerCamelCase_ = transformers.__version__ lowerCamelCase_ = 'not installed' if is_accelerate_available(): import accelerate lowerCamelCase_ = accelerate.__version__ lowerCamelCase_ = 'not installed' if is_xformers_available(): import xformers lowerCamelCase_ = xformers.__version__ lowerCamelCase_ = { '`diffusers` version': version, 'Platform': platform.platform(), 'Python version': platform.python_version(), 'PyTorch version (GPU?)': f'''{pt_version} ({pt_cuda_available})''', 'Huggingface_hub version': hub_version, 'Transformers version': transformers_version, 'Accelerate version': accelerate_version, 'xFormers version': xformers_version, 'Using GPU in script?': '<fill in>', 'Using distributed or parallel set-up in script?': '<fill in>', } print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n' ) print(self.format_dict(SCREAMING_SNAKE_CASE_ ) ) return info @staticmethod def UpperCamelCase( SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' return "\n".join([f'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
42
'''simple docstring''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Dict: '''simple docstring''' super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> List[str]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory lowerCamelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> List[str]: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}''' ) 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 (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(SCREAMING_SNAKE_CASE_ )}.''' ) # get prompt text embeddings lowerCamelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=self.tokenizer.model_max_length , return_tensors='pt' , ) lowerCamelCase_ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowerCamelCase_ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( 'The following part of your input was truncated because CLIP can only handle sequences up to' f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) lowerCamelCase_ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: lowerCamelCase_ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = text_embeddings.shape lowerCamelCase_ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) lowerCamelCase_ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # 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. lowerCamelCase_ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: lowerCamelCase_ = 42 if negative_prompt is None: lowerCamelCase_ = [''] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( f'''`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=''' f''' {type(SCREAMING_SNAKE_CASE_ )}.''' ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( f'''`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:''' f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' ' the batch size of `prompt`.' ) else: lowerCamelCase_ = negative_prompt lowerCamelCase_ = text_input_ids.shape[-1] lowerCamelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='pt' , ) lowerCamelCase_ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCamelCase_ = uncond_embeddings.shape[1] lowerCamelCase_ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) lowerCamelCase_ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCamelCase_ = 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`. lowerCamelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) lowerCamelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) lowerCamelCase_ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps lowerCamelCase_ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='cpu' , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) lowerCamelCase_ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='cpu' , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: lowerCamelCase_ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) lowerCamelCase_ = latents_reference.to(self.device ) lowerCamelCase_ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images lowerCamelCase_ = (latents_shape[3] - latents_shape_reference[3]) // 2 lowerCamelCase_ = (latents_shape[2] - latents_shape_reference[2]) // 2 lowerCamelCase_ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx lowerCamelCase_ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy lowerCamelCase_ = 0 if dx < 0 else dx lowerCamelCase_ = 0 if dy < 0 else dy lowerCamelCase_ = max(-dx , 0 ) lowerCamelCase_ = max(-dy , 0 ) # import pdb # pdb.set_trace() lowerCamelCase_ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand lowerCamelCase_ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ = 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] lowerCamelCase_ = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ = {} if accepts_eta: lowerCamelCase_ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance lowerCamelCase_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCamelCase_ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual lowerCamelCase_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: lowerCamelCase_ ,lowerCamelCase_ = noise_pred.chunk(2 ) lowerCamelCase_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 1 / 0.18_215 * latents lowerCamelCase_ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample lowerCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: lowerCamelCase_ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors='pt' ).to( self.device ) lowerCamelCase_ ,lowerCamelCase_ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: lowerCamelCase_ = None if output_type == "pil": lowerCamelCase_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
42
1
'''simple docstring''' import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class UpperCAmelCase : '''simple docstring''' def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' return None class UpperCAmelCase : '''simple docstring''' def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' return None class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = [ # (model_name, model_kwargs) ('bert-base-cased', {}), ('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def UpperCamelCase( self ) -> str: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , 'tf' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCamelCase( self ) -> List[str]: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , 'pt' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' from transformers import BertModel lowerCamelCase_ = ['[UNK]', '[SEP]', '[CLS]', '[PAD]', '[MASK]', 'some', 'other', 'words'] with NamedTemporaryFile(mode='w+t' ) as vocab_file: vocab_file.write('\n'.join(SCREAMING_SNAKE_CASE_ ) ) vocab_file.flush() lowerCamelCase_ = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: lowerCamelCase_ = BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE_ ) ) ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) self._test_export(SCREAMING_SNAKE_CASE_ , 'pt' , 12 , SCREAMING_SNAKE_CASE_ ) @require_tf @slow def UpperCamelCase( self ) -> int: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: lowerCamelCase_ = self._test_export(SCREAMING_SNAKE_CASE_ , 'tf' , 12 , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = quantize(Path(SCREAMING_SNAKE_CASE_ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) @require_torch @slow def UpperCamelCase( self ) -> str: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: lowerCamelCase_ = self._test_export(SCREAMING_SNAKE_CASE_ , 'pt' , 12 , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = quantize(SCREAMING_SNAKE_CASE_ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' try: # Compute path with TemporaryDirectory() as tempdir: lowerCamelCase_ = Path(SCREAMING_SNAKE_CASE_ ).joinpath('model.onnx' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return path except Exception as e: self.fail(SCREAMING_SNAKE_CASE_ ) @require_torch @require_tokenizers @slow def UpperCamelCase( self ) -> Tuple: '''simple docstring''' from transformers import BertModel lowerCamelCase_ = BertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) lowerCamelCase_ = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'pt' ) @require_tf @require_tokenizers @slow def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' from transformers import TFBertModel lowerCamelCase_ = TFBertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) lowerCamelCase_ = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 'tf' ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' lowerCamelCase_ = FeatureExtractionPipeline(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = ['input_ids', 'token_type_ids', 'attention_mask', 'output_0', 'output_1'] lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = infer_shapes(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Assert all variables are present self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE_ ) self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE_ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: 'batch', 1: 'sequence'} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['output_0'] , {0: 'batch', 1: 'sequence'} ) self.assertDictEqual(shapes['output_1'] , {0: 'batch'} ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = ['input_ids', 'attention_mask', 'token_type_ids'] lowerCamelCase_ = {'input_ids': [1, 2, 3, 4], 'attention_mask': [0, 0, 0, 0], 'token_type_ids': [1, 1, 1, 1]} lowerCamelCase_ ,lowerCamelCase_ = ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(SCREAMING_SNAKE_CASE_ ) , set(SCREAMING_SNAKE_CASE_ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(SCREAMING_SNAKE_CASE_ , (tokens['input_ids'], tokens['token_type_ids'], tokens['attention_mask']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) lowerCamelCase_ ,lowerCamelCase_ = ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['input_ids'] ) self.assertEqual(ordered_input_names[0] , 'input_ids' ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = generate_identified_filename(Path('/home/something/my_fake_model.onnx' ) , '-test' ) self.assertEqual('/home/something/my_fake_model-test.onnx' , generated.as_posix() )
42
'''simple docstring''' import pprint import requests A_ = "https://zenquotes.io/api" def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/today' ).json() def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": A_ = random_quotes() pprint.pprint(response)
42
1
'''simple docstring''' import math class UpperCAmelCase : '''simple docstring''' def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' lowerCamelCase_ = 0.0 lowerCamelCase_ = 0.0 for i in range(len(SCREAMING_SNAKE_CASE_ ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> list[list[int | float]]: '''simple docstring''' for i in range(len(SCREAMING_SNAKE_CASE_ ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def _UpperCamelCase ( ) -> None: # Training Examples ( m, n ) lowerCamelCase_ = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) lowerCamelCase_ = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training lowerCamelCase_ = SelfOrganizingMap() lowerCamelCase_ = 3 lowerCamelCase_ = 0.5 for _ in range(__UpperCamelCase ): for j in range(len(__UpperCamelCase ) ): # training sample lowerCamelCase_ = training_samples[j] # Compute the winning vector lowerCamelCase_ = self_organizing_map.get_winner(__UpperCamelCase ,__UpperCamelCase ) # Update the winning vector lowerCamelCase_ = self_organizing_map.update(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # classify test sample lowerCamelCase_ = [0, 0, 0, 1] lowerCamelCase_ = self_organizing_map.get_winner(__UpperCamelCase ,__UpperCamelCase ) # results print(f'''Clusters that the test sample belongs to : {winner}''' ) print(f'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
42
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=33 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ) -> int: '''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_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = num_attention_heads lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = type_vocab_size lowerCamelCase_ = type_sequence_label_size lowerCamelCase_ = initializer_range lowerCamelCase_ = num_labels lowerCamelCase_ = num_choices lowerCamelCase_ = scope def UpperCamelCase( self ) -> str: '''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 lowerCamelCase_ = None lowerCamelCase_ = None if self.use_labels: lowerCamelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase_ = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase_ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase( self ) -> List[str]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = EsmModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = EsmForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' lowerCamelCase_ = self.num_labels lowerCamelCase_ = EsmForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) = config_and_inputs lowerCamelCase_ = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ = () SCREAMING_SNAKE_CASE_ = ( { 'feature-extraction': EsmModel, 'fill-mask': EsmForMaskedLM, 'text-classification': EsmForSequenceClassification, 'token-classification': EsmForTokenClassification, 'zero-shot': EsmForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = EsmModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> str: '''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(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ = EsmModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()[0] lowerCamelCase_ = EsmEmbeddings(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) lowerCamelCase_ = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) lowerCamelCase_ = create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE_ , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()[0] lowerCamelCase_ = EsmEmbeddings(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.empty(2 , 4 , 30 ) lowerCamelCase_ = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] lowerCamelCase_ = torch.as_tensor([expected_single_positions, expected_single_positions] ) lowerCamelCase_ = embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE_ ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) @unittest.skip('Esm does not support embedding resizing' ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' pass @unittest.skip('Esm does not support embedding resizing' ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass @require_torch class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' with torch.no_grad(): lowerCamelCase_ = EsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() lowerCamelCase_ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )[0] lowerCamelCase_ = 33 lowerCamelCase_ = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCamelCase( self ) -> Tuple: '''simple docstring''' with torch.no_grad(): lowerCamelCase_ = EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() lowerCamelCase_ = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )[0] # compare the actual values for a slice. lowerCamelCase_ = torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
42
1
'''simple docstring''' from __future__ import annotations import numpy as np def _UpperCamelCase ( __UpperCamelCase ) -> Tuple: return np.maximum(0 ,__UpperCamelCase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
42
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A_ = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
42
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL A_ = logging.get_logger(__name__) class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = size if size is not None else {'shortest_edge': 384} lowerCamelCase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = do_resize lowerCamelCase_ = size # Default value set here for backwards compatibility where the value in config is None lowerCamelCase_ = crop_pct if crop_pct is not None else 224 / 256 lowerCamelCase_ = resample lowerCamelCase_ = do_rescale lowerCamelCase_ = rescale_factor lowerCamelCase_ = do_normalize lowerCamelCase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCamelCase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> np.ndarray: '''simple docstring''' lowerCamelCase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) if "shortest_edge" not in size: raise ValueError(f'''Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}''' ) lowerCamelCase_ = size['shortest_edge'] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCamelCase_ = int(shortest_edge / crop_pct ) lowerCamelCase_ = get_resize_output_image_size(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE_ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE_ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> Dict: '''simple docstring''' return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> np.ndarray: '''simple docstring''' return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , 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_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ) -> PIL.Image.Image: '''simple docstring''' lowerCamelCase_ = do_resize if do_resize is not None else self.do_resize lowerCamelCase_ = crop_pct if crop_pct is not None else self.crop_pct lowerCamelCase_ = resample if resample is not None else self.resample lowerCamelCase_ = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize 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(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 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 or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError('crop_pct must be specified if size < 384.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. lowerCamelCase_ = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: lowerCamelCase_ = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , crop_pct=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: lowerCamelCase_ = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: lowerCamelCase_ = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] lowerCamelCase_ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] lowerCamelCase_ = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ )
42
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json" ), } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'xlm-prophetnet' SCREAMING_SNAKE_CASE_ = ['past_key_values'] SCREAMING_SNAKE_CASE_ = { 'num_attention_heads': 'num_encoder_attention_heads', } def __init__( self , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = "gelu" , SCREAMING_SNAKE_CASE_ = 30522 , SCREAMING_SNAKE_CASE_ = 1024 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 2 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 128 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 2 , **SCREAMING_SNAKE_CASE_ , ) -> Tuple: '''simple docstring''' lowerCamelCase_ = vocab_size lowerCamelCase_ = hidden_size lowerCamelCase_ = encoder_ffn_dim lowerCamelCase_ = num_encoder_layers lowerCamelCase_ = num_encoder_attention_heads lowerCamelCase_ = decoder_ffn_dim lowerCamelCase_ = num_decoder_layers lowerCamelCase_ = num_decoder_attention_heads lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = init_std # Normal(0, this parameter) lowerCamelCase_ = activation_function # parameters for xlmprophetnet lowerCamelCase_ = ngram lowerCamelCase_ = num_buckets lowerCamelCase_ = relative_max_distance lowerCamelCase_ = disable_ngram_loss lowerCamelCase_ = eps # 3 Types of Dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = dropout lowerCamelCase_ = use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , add_cross_attention=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @property def UpperCamelCase( self ) -> int: '''simple docstring''' return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' raise NotImplementedError( 'This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and' ' `num_decoder_layers`.' )
42
1
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): A_ = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right A_ = 128_022 A_ = 128_028 @require_sentencepiece class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = MaMaaaTokenizer SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' super().setUp() lowerCamelCase_ = ['</s>', '<unk>', '▁This', '▁is', '▁a', '▁t', 'est', '\u0120', '<pad>'] lowerCamelCase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowerCamelCase_ = Path(self.tmpdirname ) save_json(SCREAMING_SNAKE_CASE_ , save_dir / VOCAB_FILES_NAMES['vocab_file'] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(SCREAMING_SNAKE_CASE_ , save_dir / VOCAB_FILES_NAMES['spm_file'] ) lowerCamelCase_ = MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' return ( "This is a test", "This is a test", ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = '</s>' lowerCamelCase_ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '</s>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '<s>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip('Skip this test while all models are still to be uploaded.' ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' pass def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [2, 3, 4, 5, 6] , ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) lowerCamelCase_ = tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , 'This is a test' ) @slow def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = {'input_ids': [[128022, 110108, 397, 11, 38272, 2247, 124811, 285, 18105, 1586, 207, 7, 39534, 4428, 397, 1019, 18105, 1586, 207, 7, 41337, 16786, 241, 7, 20214, 17, 125690, 10398, 7, 44378, 58069, 68342, 7798, 7343, 11, 299, 33310, 4, 158, 37350, 94077, 4569, 299, 33310, 90, 4, 52840, 290, 4, 31270, 112, 299, 682, 4, 52840, 39953, 14079, 193, 52519, 90894, 17894, 120697, 11, 40445, 551, 17, 1019, 52519, 90894, 17756, 963, 11, 40445, 480, 17, 9792, 1120, 5173, 1393, 6240, 16786, 241, 120996, 28, 1245, 1393, 118240, 11123, 1019, 93612, 2691, 10618, 98058, 120409, 1928, 279, 4, 40683, 367, 178, 207, 1019, 103, 103121, 506, 65296, 5, 2], [128022, 21217, 367, 117, 125450, 128, 719, 7, 7308, 40, 93612, 12669, 1116, 16704, 71, 17785, 3699, 15592, 35, 144, 9584, 241, 11943, 713, 950, 799, 2247, 88427, 150, 149, 118813, 120706, 1019, 106906, 81518, 28, 1224, 22799, 397, 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], [128022, 1658, 123311, 5155, 5578, 4722, 279, 14947, 2366, 1120, 1197, 14, 1348, 9232, 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]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE_ , model_name='facebook/m2m100_418M' , revision='c168bae485c864188cf9aa0e4108b0b6934dc91e' , ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'facebook/m2m100_418M' SCREAMING_SNAKE_CASE_ = [ 'In my opinion, there are two levels of response from the French government.', 'NSA Affair Emphasizes Complete Lack of Debate on Intelligence', ] SCREAMING_SNAKE_CASE_ = [ 'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.', 'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement', ] # fmt: off SCREAMING_SNAKE_CASE_ = [EN_CODE, 5_93, 19_49, 11_57_81, 4, 7_15_86, 42_34, 6_06_33, 12_62_33, 4_32, 12_38_08, 1_55_92, 11_97, 11_71_32, 12_06_18, 5, 2] @classmethod def UpperCamelCase( cls ) -> int: '''simple docstring''' lowerCamelCase_ = MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en' , tgt_lang='fr' ) lowerCamelCase_ = 1 return cls def UpperCamelCase( self ) -> Dict: '''simple docstring''' self.assertEqual(self.tokenizer.get_lang_id('ar' ) , 128006 ) self.assertEqual(self.tokenizer.get_lang_id('en' ) , 128022 ) self.assertEqual(self.tokenizer.get_lang_id('ro' ) , 128076 ) self.assertEqual(self.tokenizer.get_lang_id('mr' ) , 128063 ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = self.tokenizer.get_vocab() self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.tokenizer.vocab_size ) self.assertEqual(vocab['<unk>'] , 3 ) self.assertIn(self.tokenizer.get_lang_token('en' ) , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = 'en' lowerCamelCase_ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' self.assertIn(SCREAMING_SNAKE_CASE_ , self.tokenizer.all_special_ids ) # fmt: off lowerCamelCase_ = [FR_CODE, 5364, 82, 8642, 4, 294, 47, 8, 14028, 136, 3286, 9706, 6, 90797, 6, 144012, 162, 88128, 30061, 5, 2] # fmt: on lowerCamelCase_ = self.tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = MaMaaaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertDictEqual(new_tok.lang_token_to_id , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = 'en' lowerCamelCase_ = 'fr' lowerCamelCase_ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) lowerCamelCase_ = shift_tokens_right( batch['labels'] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: lowerCamelCase_ = batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = 'mr' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('mr' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) lowerCamelCase_ = 'zh' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('zh' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = 'mr' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('mr' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) lowerCamelCase_ = 'zh' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('zh' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer._build_translation_inputs('A test' , return_tensors='pt' , src_lang='en' , tgt_lang='ar' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ) , { # en_XX, A, test, EOS 'input_ids': [[128022, 58, 4183, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 128006, } , )
42
'''simple docstring''' import colorsys from PIL import Image # type: ignore def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> float: lowerCamelCase_ = x lowerCamelCase_ = y for step in range(__UpperCamelCase ): # noqa: B007 lowerCamelCase_ = a * a - b * b + x lowerCamelCase_ = 2 * a * b + y lowerCamelCase_ = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _UpperCamelCase ( __UpperCamelCase ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _UpperCamelCase ( __UpperCamelCase ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(__UpperCamelCase ,1 ,1 ) ) def _UpperCamelCase ( __UpperCamelCase = 8_00 ,__UpperCamelCase = 6_00 ,__UpperCamelCase = -0.6 ,__UpperCamelCase = 0 ,__UpperCamelCase = 3.2 ,__UpperCamelCase = 50 ,__UpperCamelCase = True ,) -> Image.Image: lowerCamelCase_ = Image.new('RGB' ,(image_width, image_height) ) lowerCamelCase_ = img.load() # loop through the image-coordinates for image_x in range(__UpperCamelCase ): for image_y in range(__UpperCamelCase ): # determine the figure-coordinates based on the image-coordinates lowerCamelCase_ = figure_width / image_width * image_height lowerCamelCase_ = figure_center_x + (image_x / image_width - 0.5) * figure_width lowerCamelCase_ = figure_center_y + (image_y / image_height - 0.5) * figure_height lowerCamelCase_ = get_distance(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: lowerCamelCase_ = get_color_coded_rgb(__UpperCamelCase ) else: lowerCamelCase_ = get_black_and_white_rgb(__UpperCamelCase ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure A_ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
42
1
'''simple docstring''' import os def _UpperCamelCase ( ) -> Union[str, Any]: with open(os.path.dirname(__UpperCamelCase ) + '/grid.txt' ) as f: lowerCamelCase_ = [] # noqa: E741 for _ in range(20 ): l.append([int(__UpperCamelCase ) for x in f.readline().split()] ) lowerCamelCase_ = 0 # right for i in range(20 ): for j in range(17 ): lowerCamelCase_ = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: lowerCamelCase_ = temp # down for i in range(17 ): for j in range(20 ): lowerCamelCase_ = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: lowerCamelCase_ = temp # diagonal 1 for i in range(17 ): for j in range(17 ): lowerCamelCase_ = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: lowerCamelCase_ = temp # diagonal 2 for i in range(17 ): for j in range(3 ,20 ): lowerCamelCase_ = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: lowerCamelCase_ = temp return maximum if __name__ == "__main__": print(solution())
42
'''simple docstring''' from math import isclose, sqrt def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> tuple[float, float, float]: lowerCamelCase_ = point_y / 4 / point_x lowerCamelCase_ = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) lowerCamelCase_ = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) lowerCamelCase_ = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 lowerCamelCase_ = outgoing_gradient**2 + 4 lowerCamelCase_ = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) lowerCamelCase_ = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 lowerCamelCase_ = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) lowerCamelCase_ = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point lowerCamelCase_ = x_minus if isclose(__UpperCamelCase ,__UpperCamelCase ) else x_plus lowerCamelCase_ = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _UpperCamelCase ( __UpperCamelCase = 1.4 ,__UpperCamelCase = -9.6 ) -> int: lowerCamelCase_ = 0 lowerCamelCase_ = first_x_coord lowerCamelCase_ = first_y_coord lowerCamelCase_ = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = next_point(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
42
1
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = 'ylacombe/bark-small' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = 'en_speaker_1' lowerCamelCase_ = 'This is a test string' lowerCamelCase_ = 'speaker_embeddings_path.json' lowerCamelCase_ = 'speaker_embeddings' def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase_ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase_ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCamelCase_ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='(BOS)' , eos_token='(EOS)' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase_ = 35 lowerCamelCase_ = 2 lowerCamelCase_ = 8 lowerCamelCase_ = { 'semantic_prompt': np.ones(SCREAMING_SNAKE_CASE_ ), 'coarse_prompt': np.ones((nb_codebooks_coarse, seq_len) ), 'fine_prompt': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() ) # test loading voice preset from npz file lowerCamelCase_ = os.path.join(self.tmpdirname , 'file.npz' ) np.savez(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() ) # test loading voice preset from the hub lowerCamelCase_ = processor(text=self.input_string , voice_preset=self.voice_preset ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = processor(text=self.input_string ) lowerCamelCase_ = tokenizer( self.input_string , padding='max_length' , max_length=256 , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
42
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = False ) -> bool: if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3_31_70_44_06_46_79_88_73_85_96_19_81 and not allow_probable: raise ValueError( 'Warning: upper bound of deterministic test is exceeded. ' 'Pass allow_probable=True to allow probabilistic test. ' 'A return value of True indicates a probable prime.' ) # array bounds provided by analysis lowerCamelCase_ = [ 20_47, 1_37_36_53, 25_32_60_01, 32_15_03_17_51, 2_15_23_02_89_87_47, 3_47_47_49_66_03_83, 3_41_55_00_71_72_83_21, 1, 3_82_51_23_05_65_46_41_30_51, 1, 1, 31_86_65_85_78_34_03_11_51_16_74_61, 3_31_70_44_06_46_79_88_73_85_96_19_81, ] lowerCamelCase_ = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(__UpperCamelCase ,1 ): if n < _p: # then we have our last prime to check lowerCamelCase_ = primes[:idx] break lowerCamelCase_ ,lowerCamelCase_ = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: lowerCamelCase_ = False for r in range(__UpperCamelCase ): lowerCamelCase_ = pow(__UpperCamelCase ,d * 2**r ,__UpperCamelCase ) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): lowerCamelCase_ = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True def _UpperCamelCase ( ) -> None: assert not miller_rabin(5_61 ) assert miller_rabin(5_63 ) # 2047 assert not miller_rabin(83_82_01 ) assert miller_rabin(83_82_07 ) # 1_373_653 assert not miller_rabin(17_31_60_01 ) assert miller_rabin(17_31_60_17 ) # 25_326_001 assert not miller_rabin(30_78_38_66_41 ) assert miller_rabin(30_78_38_66_53 ) # 3_215_031_751 assert not miller_rabin(1_71_30_45_57_48_01 ) assert miller_rabin(1_71_30_45_57_48_19 ) # 2_152_302_898_747 assert not miller_rabin(2_77_97_99_72_83_07 ) assert miller_rabin(2_77_97_99_72_83_27 ) # 3_474_749_660_383 assert not miller_rabin(1_13_85_00_23_90_94_41 ) assert miller_rabin(1_13_85_00_23_90_95_27 ) # 341_550_071_728_321 assert not miller_rabin(1_27_50_41_01_88_48_80_43_51 ) assert miller_rabin(1_27_50_41_01_88_48_80_43_91 ) # 3_825_123_056_546_413_051 assert not miller_rabin(7_96_66_46_44_58_50_77_87_79_18_67 ) assert miller_rabin(7_96_66_46_44_58_50_77_87_79_19_51 ) # 318_665_857_834_031_151_167_461 assert not miller_rabin(55_28_40_67_74_46_64_78_97_66_03_33 ) assert miller_rabin(55_28_40_67_74_46_64_78_97_66_03_59 ) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
42
1
'''simple docstring''' import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=10_24 ) -> str: lowerCamelCase_ ,lowerCamelCase_ = [], [] lowerCamelCase_ = list(zip(__UpperCamelCase ,__UpperCamelCase ) ) lowerCamelCase_ ,lowerCamelCase_ = sorted_examples[0] def is_too_big(__UpperCamelCase ): return tok(__UpperCamelCase ,return_tensors='pt' ).input_ids.shape[1] > max_tokens for src, tgt in tqdm(sorted_examples[1:] ): lowerCamelCase_ = new_src + ' ' + src lowerCamelCase_ = new_tgt + ' ' + tgt if is_too_big(__UpperCamelCase ) or is_too_big(__UpperCamelCase ): # cant fit, finalize example finished_src.append(__UpperCamelCase ) finished_tgt.append(__UpperCamelCase ) lowerCamelCase_ ,lowerCamelCase_ = src, tgt else: # can fit, keep adding lowerCamelCase_ ,lowerCamelCase_ = cand_src, cand_tgt # cleanup if new_src: assert new_tgt finished_src.append(__UpperCamelCase ) finished_tgt.append(__UpperCamelCase ) return finished_src, finished_tgt def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> List[Any]: lowerCamelCase_ = Path(__UpperCamelCase ) save_path.mkdir(exist_ok=__UpperCamelCase ) for split in ["train"]: lowerCamelCase_ ,lowerCamelCase_ = data_dir / f'''{split}.source''', data_dir / f'''{split}.target''' lowerCamelCase_ = [x.rstrip() for x in Path(__UpperCamelCase ).open().readlines()] lowerCamelCase_ = [x.rstrip() for x in Path(__UpperCamelCase ).open().readlines()] lowerCamelCase_ ,lowerCamelCase_ = pack_examples(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) print(f'''packed {split} split from {len(__UpperCamelCase )} examples -> {len(__UpperCamelCase )}.''' ) Path(save_path / f'''{split}.source''' ).open('w' ).write('\n'.join(__UpperCamelCase ) ) Path(save_path / f'''{split}.target''' ).open('w' ).write('\n'.join(__UpperCamelCase ) ) for split in ["val", "test"]: lowerCamelCase_ ,lowerCamelCase_ = data_dir / f'''{split}.source''', data_dir / f'''{split}.target''' shutil.copyfile(__UpperCamelCase ,save_path / f'''{split}.source''' ) shutil.copyfile(__UpperCamelCase ,save_path / f'''{split}.target''' ) def _UpperCamelCase ( ) -> List[str]: lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument('--tok_name' ,type=__UpperCamelCase ,help='like facebook/bart-large-cnn,t5-base, etc.' ) parser.add_argument('--max_seq_len' ,type=__UpperCamelCase ,default=1_28 ) parser.add_argument('--data_dir' ,type=__UpperCamelCase ) parser.add_argument('--save_path' ,type=__UpperCamelCase ) lowerCamelCase_ = parser.parse_args() lowerCamelCase_ = AutoTokenizer.from_pretrained(args.tok_name ) return pack_data_dir(__UpperCamelCase ,Path(args.data_dir ) ,args.max_seq_len ,args.save_path ) if __name__ == "__main__": packer_cli()
42
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler A_ = 16 A_ = 32 def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = 16 ,__UpperCamelCase = "bert-base-cased" ) -> List[Any]: lowerCamelCase_ = AutoTokenizer.from_pretrained(__UpperCamelCase ) lowerCamelCase_ = load_dataset('glue' ,'mrpc' ) def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) lowerCamelCase_ = tokenizer(examples['sentence1'] ,examples['sentence2'] ,truncation=__UpperCamelCase ,max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowerCamelCase_ = datasets.map( __UpperCamelCase ,batched=__UpperCamelCase ,remove_columns=['idx', 'sentence1', 'sentence2'] ,load_from_cache_file=__UpperCamelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCamelCase_ = tokenized_datasets.rename_column('label' ,'labels' ) 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. lowerCamelCase_ = DataLoader( tokenized_datasets['train'] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) lowerCamelCase_ = DataLoader( tokenized_datasets['validation'] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Union[str, Any]: model.eval() lowerCamelCase_ = 0 for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times lowerCamelCase_ ,lowerCamelCase_ = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__UpperCamelCase ) - 1: lowerCamelCase_ = predictions[: len(eval_dataloader.dataset ) - samples_seen] lowerCamelCase_ = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__UpperCamelCase ,references=__UpperCamelCase ,) lowerCamelCase_ = metric.compute() return eval_metric["accuracy"] def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> List[str]: # Initialize accelerator lowerCamelCase_ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCamelCase_ = config['lr'] lowerCamelCase_ = int(config['num_epochs'] ) lowerCamelCase_ = int(config['seed'] ) lowerCamelCase_ = int(config['batch_size'] ) lowerCamelCase_ = args.model_name_or_path set_seed(__UpperCamelCase ) lowerCamelCase_ ,lowerCamelCase_ = get_dataloaders(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCamelCase_ = AutoModelForSequenceClassification.from_pretrained(__UpperCamelCase ,return_dict=__UpperCamelCase ) # Instantiate optimizer lowerCamelCase_ = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowerCamelCase_ = optimizer_cls(params=model.parameters() ,lr=__UpperCamelCase ) if accelerator.state.deepspeed_plugin is not None: lowerCamelCase_ = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: lowerCamelCase_ = 1 lowerCamelCase_ = (len(__UpperCamelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowerCamelCase_ = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase ,num_warmup_steps=0 ,num_training_steps=__UpperCamelCase ,) else: lowerCamelCase_ = DummyScheduler(__UpperCamelCase ,total_num_steps=__UpperCamelCase ,warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = accelerator.prepare( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # We need to keep track of how many total steps we have iterated over lowerCamelCase_ = 0 # We also need to keep track of the stating epoch so files are named properly lowerCamelCase_ = 0 lowerCamelCase_ = evaluate.load('glue' ,'mrpc' ) lowerCamelCase_ = num_epochs if args.partial_train_epoch is not None: lowerCamelCase_ = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) lowerCamelCase_ = args.resume_from_checkpoint.split('epoch_' )[1] lowerCamelCase_ = '' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break lowerCamelCase_ = int(__UpperCamelCase ) + 1 lowerCamelCase_ = evaluation_loop(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) accelerator.print('resumed checkpoint performance:' ,__UpperCamelCase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:' ,lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:' ,optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir ,f'''state_{starting_epoch-1}.json''' ) ,'r' ) as f: lowerCamelCase_ = json.load(__UpperCamelCase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model lowerCamelCase_ = {} for epoch in range(__UpperCamelCase ,__UpperCamelCase ): model.train() for step, batch in enumerate(__UpperCamelCase ): lowerCamelCase_ = model(**__UpperCamelCase ) lowerCamelCase_ = outputs.loss lowerCamelCase_ = loss / gradient_accumulation_steps accelerator.backward(__UpperCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 lowerCamelCase_ = f'''epoch_{epoch}''' lowerCamelCase_ = os.path.join(args.output_dir ,__UpperCamelCase ) accelerator.save_state(__UpperCamelCase ) lowerCamelCase_ = evaluation_loop(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) lowerCamelCase_ = accuracy lowerCamelCase_ = lr_scheduler.get_lr()[0] lowerCamelCase_ = optimizer.param_groups[0]['lr'] lowerCamelCase_ = epoch lowerCamelCase_ = overall_step accelerator.print(f'''epoch {epoch}:''' ,__UpperCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,f'''state_{epoch}.json''' ) ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( ) -> str: lowerCamelCase_ = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' ,type=__UpperCamelCase ,default='bert-base-cased' ,help='Path to pretrained model or model identifier from huggingface.co/models.' ,required=__UpperCamelCase ,) parser.add_argument( '--output_dir' ,type=__UpperCamelCase ,default='.' ,help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' ,) parser.add_argument( '--resume_from_checkpoint' ,type=__UpperCamelCase ,default=__UpperCamelCase ,help='If the training should continue from a checkpoint folder.' ,) parser.add_argument( '--partial_train_epoch' ,type=__UpperCamelCase ,default=__UpperCamelCase ,help='If passed, the training will stop after this number of epochs.' ,) parser.add_argument( '--num_epochs' ,type=__UpperCamelCase ,default=2 ,help='Number of train epochs.' ,) lowerCamelCase_ = parser.parse_args() lowerCamelCase_ = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(__UpperCamelCase ,__UpperCamelCase ) if __name__ == "__main__": main()
42
1
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, 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 A_ = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A_ = 250_004 A_ = 250_020 @require_sentencepiece @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = MBartTokenizer SCREAMING_SNAKE_CASE_ = MBartTokenizerFast SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase_ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase_ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def UpperCamelCase( self ) -> int: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase_ = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCamelCase_ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) lowerCamelCase_ = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=True lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=False lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'facebook/mbart-large-en-ro' SCREAMING_SNAKE_CASE_ = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] SCREAMING_SNAKE_CASE_ = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] SCREAMING_SNAKE_CASE_ = [82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2, EN_CODE] @classmethod def UpperCamelCase( cls ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) lowerCamelCase_ = 1 return cls def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 250020 ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' self.assertIn(SCREAMING_SNAKE_CASE_ , self.tokenizer.all_special_ids ) lowerCamelCase_ = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] lowerCamelCase_ = self.tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 10 lowerCamelCase_ = self.tokenizer(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [250026, 250001] ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = MBartTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) lowerCamelCase_ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=3 , return_tensors='pt' ) lowerCamelCase_ = self.tokenizer( text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=10 , return_tensors='pt' ) lowerCamelCase_ = targets['input_ids'] lowerCamelCase_ = shift_tokens_right(SCREAMING_SNAKE_CASE_ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ) , { # A, test, EOS, en_XX 'input_ids': [[62, 3034, 2, 250004]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 250001, } , )
42
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> np.ndarray: # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: lowerCamelCase_ = ksize + 1 lowerCamelCase_ = np.zeros((ksize, ksize) ,dtype=np.floataa ) # each value for y in range(__UpperCamelCase ): for x in range(__UpperCamelCase ): # distance from center lowerCamelCase_ = x - ksize // 2 lowerCamelCase_ = y - ksize // 2 # degree to radiant lowerCamelCase_ = theta / 1_80 * np.pi lowerCamelCase_ = np.cos(_theta ) lowerCamelCase_ = np.sin(_theta ) # get kernel x lowerCamelCase_ = cos_theta * px + sin_theta * py # get kernel y lowerCamelCase_ = -sin_theta * px + cos_theta * py # fill kernel lowerCamelCase_ = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image A_ = imread("../image_data/lena.jpg") # turn image in gray scale value A_ = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges A_ = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: A_ = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) A_ = out / out.max() * 255 A_ = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
42
1
'''simple docstring''' import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> str: lowerCamelCase_ = WavaVecaForSequenceClassification.from_pretrained(__UpperCamelCase ,config=__UpperCamelCase ) lowerCamelCase_ = downstream_dict['projector.weight'] lowerCamelCase_ = downstream_dict['projector.bias'] lowerCamelCase_ = downstream_dict['model.post_net.linear.weight'] lowerCamelCase_ = downstream_dict['model.post_net.linear.bias'] return model def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Tuple: lowerCamelCase_ = WavaVecaForAudioFrameClassification.from_pretrained(__UpperCamelCase ,config=__UpperCamelCase ) lowerCamelCase_ = downstream_dict['model.linear.weight'] lowerCamelCase_ = downstream_dict['model.linear.bias'] return model def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Tuple: lowerCamelCase_ = WavaVecaForXVector.from_pretrained(__UpperCamelCase ,config=__UpperCamelCase ) lowerCamelCase_ = downstream_dict['connector.weight'] lowerCamelCase_ = downstream_dict['connector.bias'] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): lowerCamelCase_ = downstream_dict[ f'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] lowerCamelCase_ = downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] lowerCamelCase_ = downstream_dict['model.utterancelevel_feature_extractor.linear1.weight'] lowerCamelCase_ = downstream_dict['model.utterancelevel_feature_extractor.linear1.bias'] lowerCamelCase_ = downstream_dict['model.utterancelevel_feature_extractor.linear2.weight'] lowerCamelCase_ = downstream_dict['model.utterancelevel_feature_extractor.linear2.bias'] lowerCamelCase_ = downstream_dict['objective.W'] return model @torch.no_grad() def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Dict: lowerCamelCase_ = torch.load(__UpperCamelCase ,map_location='cpu' ) lowerCamelCase_ = checkpoint['Downstream'] lowerCamelCase_ = WavaVecaConfig.from_pretrained(__UpperCamelCase ) lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained( __UpperCamelCase ,return_attention_mask=__UpperCamelCase ,do_normalize=__UpperCamelCase ) lowerCamelCase_ = hf_config.architectures[0] if arch.endswith('ForSequenceClassification' ): lowerCamelCase_ = convert_classification(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) elif arch.endswith('ForAudioFrameClassification' ): lowerCamelCase_ = convert_diarization(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) elif arch.endswith('ForXVector' ): lowerCamelCase_ = convert_xvector(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) else: raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: lowerCamelCase_ = checkpoint['Featurizer']['weights'] hf_feature_extractor.save_pretrained(__UpperCamelCase ) hf_model.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument( "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model." ) parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.") parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.") A_ = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
42
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['transformers', 'torch', 'note_seq'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['transformers', 'torch', 'note_seq'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['transformers', 'torch', 'note_seq'] ) @classmethod def UpperCamelCase( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' requires_backends(cls , ['transformers', 'torch', 'note_seq'] )
42
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ = { "configuration_clipseg": [ "CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPSegConfig", "CLIPSegTextConfig", "CLIPSegVisionConfig", ], "processing_clipseg": ["CLIPSegProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPSegModel", "CLIPSegPreTrainedModel", "CLIPSegTextModel", "CLIPSegVisionModel", "CLIPSegForImageSegmentation", ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
42
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def UpperCamelCase( self ) -> int: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , ) return model @property def UpperCamelCase( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase_ = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) lowerCamelCase_ = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) lowerCamelCase_ = DDPMScheduler() lowerCamelCase_ = AudioDiffusionPipeline(vqvae=SCREAMING_SNAKE_CASE_ , unet=self.dummy_unet , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , steps=4 ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = output.images[0] lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , steps=4 , return_dict=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 lowerCamelCase_ = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) lowerCamelCase_ = DDIMScheduler() lowerCamelCase_ = self.dummy_vqvae_and_unet lowerCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) np.random.seed(0 ) lowerCamelCase_ = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(raw_audio=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , start_step=5 , steps=10 ) lowerCamelCase_ = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 lowerCamelCase_ = self.dummy_unet_condition lowerCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=SCREAMING_SNAKE_CASE_ , mel=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) np.random.seed(0 ) lowerCamelCase_ = torch.rand((1, 1, 10) ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ , encoding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.images[0] lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = torch_device lowerCamelCase_ = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) lowerCamelCase_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(42 ) lowerCamelCase_ = pipe(generator=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = output.audios[0] lowerCamelCase_ = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] lowerCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] lowerCamelCase_ = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
42
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ = {"configuration_xlnet": ["XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["XLNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["XLNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "XLNET_PRETRAINED_MODEL_ARCHIVE_LIST", "XLNetForMultipleChoice", "XLNetForQuestionAnswering", "XLNetForQuestionAnsweringSimple", "XLNetForSequenceClassification", "XLNetForTokenClassification", "XLNetLMHeadModel", "XLNetModel", "XLNetPreTrainedModel", "load_tf_weights_in_xlnet", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLNetForMultipleChoice", "TFXLNetForQuestionAnsweringSimple", "TFXLNetForSequenceClassification", "TFXLNetForTokenClassification", "TFXLNetLMHeadModel", "TFXLNetMainLayer", "TFXLNetModel", "TFXLNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
42
'''simple docstring''' import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _UpperCamelCase ( __UpperCamelCase = 8 ) -> str: lowerCamelCase_ = ascii_letters + digits + punctuation return "".join(secrets.choice(__UpperCamelCase ) for _ in range(__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(__UpperCamelCase ) lowerCamelCase_ = i // 3 lowerCamelCase_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) lowerCamelCase_ = ( chars_incl + random(__UpperCamelCase ,quotient + remainder ) + random(__UpperCamelCase ,__UpperCamelCase ) + random(__UpperCamelCase ,__UpperCamelCase ) ) lowerCamelCase_ = list(__UpperCamelCase ) shuffle(__UpperCamelCase ) return "".join(__UpperCamelCase ) # random is a generalised function for letters, characters and numbers def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: return "".join(secrets.choice(__UpperCamelCase ) for _ in range(__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Optional[int]: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Tuple: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> str: pass # Put your code here... def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase = 8 ) -> bool: if len(__UpperCamelCase ) < min_length: # Your Password must be at least 8 characters long return False lowerCamelCase_ = any(char in ascii_uppercase for char in password ) lowerCamelCase_ = any(char in ascii_lowercase for char in password ) lowerCamelCase_ = any(char in digits for char in password ) lowerCamelCase_ = 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 _UpperCamelCase ( ) -> Optional[int]: lowerCamelCase_ = int(input('Please indicate the max length of your password: ' ).strip() ) lowerCamelCase_ = input( 'Please indicate the characters that must be in your password: ' ).strip() print('Password generated:' ,password_generator(__UpperCamelCase ) ) print( 'Alternative Password generated:' ,alternative_password_generator(__UpperCamelCase ,__UpperCamelCase ) ,) print('[If you are thinking of using this passsword, You better save it.]' ) if __name__ == "__main__": main()
42
1
'''simple docstring''' from collections import deque class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None: '''simple docstring''' lowerCamelCase_ = process_name # process name lowerCamelCase_ = arrival_time # arrival time of the process # completion time of finished process or last interrupted time lowerCamelCase_ = arrival_time lowerCamelCase_ = burst_time # remaining burst time lowerCamelCase_ = 0 # total time of the process wait in ready queue lowerCamelCase_ = 0 # time from arrival time to completion time class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> None: '''simple docstring''' lowerCamelCase_ = number_of_queues # time slice of queues that round robin algorithm applied lowerCamelCase_ = time_slices # unfinished process is in this ready_queue lowerCamelCase_ = queue # current time lowerCamelCase_ = current_time # finished process is in this sequence queue lowerCamelCase_ = deque() def UpperCamelCase( self ) -> list[str]: '''simple docstring''' lowerCamelCase_ = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> list[int]: '''simple docstring''' lowerCamelCase_ = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> list[int]: '''simple docstring''' lowerCamelCase_ = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> list[int]: '''simple docstring''' lowerCamelCase_ = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): completion_times.append(queue[i].stop_time ) return completion_times def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> list[int]: '''simple docstring''' return [q.burst_time for q in queue] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' process.waiting_time += self.current_time - process.stop_time return process.waiting_time def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> deque[Process]: '''simple docstring''' lowerCamelCase_ = deque() # sequence deque of finished process while len(SCREAMING_SNAKE_CASE_ ) != 0: lowerCamelCase_ = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 lowerCamelCase_ = 0 # set the process's turnaround time because it is finished lowerCamelCase_ = self.current_time - cp.arrival_time # set the completion time lowerCamelCase_ = self.current_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> tuple[deque[Process], deque[Process]]: '''simple docstring''' lowerCamelCase_ = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(SCREAMING_SNAKE_CASE_ ) ): lowerCamelCase_ = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time lowerCamelCase_ = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(SCREAMING_SNAKE_CASE_ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished lowerCamelCase_ = 0 # set the finish time lowerCamelCase_ = self.current_time # update the process' turnaround time because it is finished lowerCamelCase_ = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def UpperCamelCase( self ) -> deque[Process]: '''simple docstring''' for i in range(self.number_of_queues - 1 ): lowerCamelCase_ ,lowerCamelCase_ = 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_ = Process("P1", 0, 53) A_ = Process("P2", 0, 17) A_ = Process("P3", 0, 68) A_ = Process("P4", 0, 24) A_ = 3 A_ = [17, 25] A_ = 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_ = Process("P1", 0, 53) A_ = Process("P2", 0, 17) A_ = Process("P3", 0, 68) A_ = Process("P4", 0, 24) A_ = 3 A_ = [17, 25] A_ = deque([Pa, Pa, Pa, Pa]) A_ = MLFQ(number_of_queues, time_slices, queue, 0) A_ = 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()}''' )
42
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 lowerCamelCase_ = test_metrics @require_cpu def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def UpperCamelCase( self ) -> Tuple: '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def UpperCamelCase( self ) -> Any: '''simple docstring''' self.test_metrics.main() @require_multi_gpu def UpperCamelCase( self ) -> Any: '''simple docstring''' print(f'''Found {torch.cuda.device_count()} devices.''' ) lowerCamelCase_ = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() )
42
1
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} A_ = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } A_ = { "allenai/longformer-base-4096": 4_096, "allenai/longformer-large-4096": 4_096, "allenai/longformer-large-4096-finetuned-triviaqa": 4_096, "allenai/longformer-base-4096-extra.pos.embd.only": 4_096, "allenai/longformer-large-4096-extra.pos.embd.only": 4_096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _UpperCamelCase ( ) -> Any: lowerCamelCase_ = ( list(range(ord('!' ) ,ord('~' ) + 1 ) ) + list(range(ord('¡' ) ,ord('¬' ) + 1 ) ) + list(range(ord('®' ) ,ord('ÿ' ) + 1 ) ) ) lowerCamelCase_ = bs[:] lowerCamelCase_ = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 lowerCamelCase_ = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase ,__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: lowerCamelCase_ = set() lowerCamelCase_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCamelCase_ = char return pairs class UpperCAmelCase ( UpperCAmelCase__ ): '''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 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="replace" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else bos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else eos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else sep_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else cls_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else unk_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( errors=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as vocab_handle: lowerCamelCase_ = json.load(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {v: k for k, v in self.encoder.items()} lowerCamelCase_ = errors # how to handle errors in decoding lowerCamelCase_ = bytes_to_unicode() lowerCamelCase_ = {v: k for k, v in self.byte_encoder.items()} with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as merges_handle: lowerCamelCase_ = merges_handle.read().split('\n' )[1:-1] lowerCamelCase_ = [tuple(merge.split() ) for merge in bpe_merges] lowerCamelCase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowerCamelCase_ = {} lowerCamelCase_ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowerCamelCase_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' return len(self.encoder ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' if token in self.cache: return self.cache[token] lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) if not pairs: return token while True: lowerCamelCase_ = min(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break lowerCamelCase_ ,lowerCamelCase_ = bigram lowerCamelCase_ = [] lowerCamelCase_ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): try: lowerCamelCase_ = word.index(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCamelCase_ = j if word[i] == first and i < len(SCREAMING_SNAKE_CASE_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = new_word if len(SCREAMING_SNAKE_CASE_ ) == 1: break else: lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = ' '.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = word return word def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' lowerCamelCase_ = [] for token in re.findall(self.pat , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(SCREAMING_SNAKE_CASE_ ).split(' ' ) ) return bpe_tokens def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' return self.encoder.get(SCREAMING_SNAKE_CASE_ , self.encoder.get(self.unk_token ) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' return self.decoder.get(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = ''.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) + '\n' ) lowerCamelCase_ = 0 with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ' Please check that the tokenizer is not corrupted!' ) lowerCamelCase_ = token_index writer.write(' '.join(SCREAMING_SNAKE_CASE_ ) + '\n' ) index += 1 return vocab_file, merge_file def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] lowerCamelCase_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' lowerCamelCase_ = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(SCREAMING_SNAKE_CASE_ ) > 0 and not text[0].isspace()): lowerCamelCase_ = ' ' + text return (text, kwargs)
42
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True) os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True) os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: if hor == 1_28: lowerCamelCase_ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') lowerCamelCase_ = (32, 1_28, 2_56) lowerCamelCase_ = ('UpResnetBlock1D', 'UpResnetBlock1D') elif hor == 32: lowerCamelCase_ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') lowerCamelCase_ = (32, 64, 1_28, 2_56) lowerCamelCase_ = ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D') lowerCamelCase_ = torch.load(f'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' ) lowerCamelCase_ = model.state_dict() lowerCamelCase_ = { 'down_block_types': down_block_types, 'block_out_channels': block_out_channels, 'up_block_types': up_block_types, 'layers_per_block': 1, 'use_timestep_embedding': True, 'out_block_type': 'OutConv1DBlock', 'norm_num_groups': 8, 'downsample_each_block': False, 'in_channels': 14, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'flip_sin_to_cos': False, 'freq_shift': 1, 'sample_size': 6_55_36, 'mid_block_type': 'MidResTemporalBlock1D', 'act_fn': 'mish', } lowerCamelCase_ = UNetaDModel(**__UpperCamelCase ) print(f'''length of state dict: {len(state_dict.keys() )}''' ) print(f'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) lowerCamelCase_ = dict(zip(model.state_dict().keys() ,hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): lowerCamelCase_ = state_dict.pop(__UpperCamelCase ) hf_value_function.load_state_dict(__UpperCamelCase ) torch.save(hf_value_function.state_dict() ,f'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' ) with open(f'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) def _UpperCamelCase ( ) -> Tuple: lowerCamelCase_ = { 'in_channels': 14, 'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'), 'up_block_types': (), 'out_block_type': 'ValueFunction', 'mid_block_type': 'ValueFunctionMidBlock1D', 'block_out_channels': (32, 64, 1_28, 2_56), 'layers_per_block': 1, 'downsample_each_block': True, 'sample_size': 6_55_36, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'use_timestep_embedding': True, 'flip_sin_to_cos': False, 'freq_shift': 1, 'norm_num_groups': 8, 'act_fn': 'mish', } lowerCamelCase_ = torch.load('/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch' ) lowerCamelCase_ = model lowerCamelCase_ = UNetaDModel(**__UpperCamelCase ) print(f'''length of state dict: {len(state_dict.keys() )}''' ) print(f'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' ) lowerCamelCase_ = dict(zip(state_dict.keys() ,hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): lowerCamelCase_ = state_dict.pop(__UpperCamelCase ) hf_value_function.load_state_dict(__UpperCamelCase ) torch.save(hf_value_function.state_dict() ,'hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin' ) with open('hub/hopper-medium-v2/value_function/config.json' ,'w' ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) if __name__ == "__main__": unet(32) # unet(128) value_function()
42
1
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed A_ = { "distilbert": (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), "roberta": (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), "bert": (BertConfig, BertForMaskedLM, BertTokenizer), "gpt2": (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def _UpperCamelCase ( __UpperCamelCase ) -> int: assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> List[Any]: if args.student_type == "roberta": lowerCamelCase_ = False elif args.student_type == "gpt2": lowerCamelCase_ = False def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Any: if args.student_type == "roberta": lowerCamelCase_ = False def _UpperCamelCase ( ) -> Any: lowerCamelCase_ = argparse.ArgumentParser(description='Training' ) parser.add_argument('--force' ,action='store_true' ,help='Overwrite dump_path if it already exists.' ) parser.add_argument( '--dump_path' ,type=__UpperCamelCase ,required=__UpperCamelCase ,help='The output directory (log, checkpoints, parameters, etc.)' ) parser.add_argument( '--data_file' ,type=__UpperCamelCase ,required=__UpperCamelCase ,help='The binarized file (tokenized + tokens_to_ids) and grouped by sequence.' ,) parser.add_argument( '--student_type' ,type=__UpperCamelCase ,choices=['distilbert', 'roberta', 'gpt2'] ,required=__UpperCamelCase ,help='The student type (DistilBERT, RoBERTa).' ,) parser.add_argument('--student_config' ,type=__UpperCamelCase ,required=__UpperCamelCase ,help='Path to the student configuration.' ) parser.add_argument( '--student_pretrained_weights' ,default=__UpperCamelCase ,type=__UpperCamelCase ,help='Load student initialization checkpoint.' ) parser.add_argument( '--teacher_type' ,choices=['bert', 'roberta', 'gpt2'] ,required=__UpperCamelCase ,help='Teacher type (BERT, RoBERTa).' ) parser.add_argument('--teacher_name' ,type=__UpperCamelCase ,required=__UpperCamelCase ,help='The teacher model.' ) parser.add_argument('--temperature' ,default=2.0 ,type=__UpperCamelCase ,help='Temperature for the softmax temperature.' ) parser.add_argument( '--alpha_ce' ,default=0.5 ,type=__UpperCamelCase ,help='Linear weight for the distillation loss. Must be >=0.' ) parser.add_argument( '--alpha_mlm' ,default=0.0 ,type=__UpperCamelCase ,help='Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.' ,) parser.add_argument('--alpha_clm' ,default=0.5 ,type=__UpperCamelCase ,help='Linear weight for the CLM loss. Must be >=0.' ) parser.add_argument('--alpha_mse' ,default=0.0 ,type=__UpperCamelCase ,help='Linear weight of the MSE loss. Must be >=0.' ) parser.add_argument( '--alpha_cos' ,default=0.0 ,type=__UpperCamelCase ,help='Linear weight of the cosine embedding loss. Must be >=0.' ) parser.add_argument( '--mlm' ,action='store_true' ,help='The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.' ) parser.add_argument( '--mlm_mask_prop' ,default=0.15 ,type=__UpperCamelCase ,help='Proportion of tokens for which we need to make a prediction.' ,) parser.add_argument('--word_mask' ,default=0.8 ,type=__UpperCamelCase ,help='Proportion of tokens to mask out.' ) parser.add_argument('--word_keep' ,default=0.1 ,type=__UpperCamelCase ,help='Proportion of tokens to keep.' ) parser.add_argument('--word_rand' ,default=0.1 ,type=__UpperCamelCase ,help='Proportion of tokens to randomly replace.' ) parser.add_argument( '--mlm_smoothing' ,default=0.7 ,type=__UpperCamelCase ,help='Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).' ,) parser.add_argument('--token_counts' ,type=__UpperCamelCase ,help='The token counts in the data_file for MLM.' ) parser.add_argument( '--restrict_ce_to_mask' ,action='store_true' ,help='If true, compute the distillation loss only the [MLM] prediction distribution.' ,) parser.add_argument( '--freeze_pos_embs' ,action='store_true' ,help='Freeze positional embeddings during distillation. For student_type in [\'roberta\', \'gpt2\'] only.' ,) parser.add_argument( '--freeze_token_type_embds' ,action='store_true' ,help='Freeze token type embeddings during distillation if existent. For student_type in [\'roberta\'] only.' ,) parser.add_argument('--n_epoch' ,type=__UpperCamelCase ,default=3 ,help='Number of pass on the whole dataset.' ) parser.add_argument('--batch_size' ,type=__UpperCamelCase ,default=5 ,help='Batch size (for each process).' ) parser.add_argument( '--group_by_size' ,action='store_false' ,help='If true, group sequences that have similar length into the same batch. Default is true.' ,) parser.add_argument( '--gradient_accumulation_steps' ,type=__UpperCamelCase ,default=50 ,help='Gradient accumulation for larger training batches.' ,) parser.add_argument('--warmup_prop' ,default=0.05 ,type=__UpperCamelCase ,help='Linear warmup proportion.' ) parser.add_argument('--weight_decay' ,default=0.0 ,type=__UpperCamelCase ,help='Weight decay if we apply some.' ) parser.add_argument('--learning_rate' ,default=5e-4 ,type=__UpperCamelCase ,help='The initial learning rate for Adam.' ) parser.add_argument('--adam_epsilon' ,default=1e-6 ,type=__UpperCamelCase ,help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' ,default=5.0 ,type=__UpperCamelCase ,help='Max gradient norm.' ) parser.add_argument('--initializer_range' ,default=0.02 ,type=__UpperCamelCase ,help='Random initialization range.' ) parser.add_argument( '--fp16' ,action='store_true' ,help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit' ,) parser.add_argument( '--fp16_opt_level' ,type=__UpperCamelCase ,default='O1' ,help=( 'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].' 'See details at https://nvidia.github.io/apex/amp.html' ) ,) parser.add_argument('--n_gpu' ,type=__UpperCamelCase ,default=1 ,help='Number of GPUs in the node.' ) parser.add_argument('--local_rank' ,type=__UpperCamelCase ,default=-1 ,help='Distributed training - Local rank' ) parser.add_argument('--seed' ,type=__UpperCamelCase ,default=56 ,help='Random seed' ) parser.add_argument('--log_interval' ,type=__UpperCamelCase ,default=5_00 ,help='Tensorboard logging interval.' ) parser.add_argument('--checkpoint_interval' ,type=__UpperCamelCase ,default=40_00 ,help='Checkpoint interval.' ) lowerCamelCase_ = parser.parse_args() sanity_checks(__UpperCamelCase ) # ARGS # init_gpu_params(__UpperCamelCase ) set_seed(__UpperCamelCase ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f'''Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite''' ' itUse `--force` if you want to overwrite it' ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f'''Experiment will be dumped and logged in {args.dump_path}''' ) # SAVE PARAMS # logger.info(f'''Param: {args}''' ) with open(os.path.join(args.dump_path ,'parameters.json' ) ,'w' ) as f: json.dump(vars(__UpperCamelCase ) ,__UpperCamelCase ,indent=4 ) git_log(args.dump_path ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = MODEL_CLASSES[args.student_type] lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # lowerCamelCase_ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) lowerCamelCase_ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): lowerCamelCase_ = tokenizer.all_special_tokens.index(__UpperCamelCase ) lowerCamelCase_ = tokenizer.all_special_ids[idx] logger.info(f'''Special tokens {special_tok_ids}''' ) lowerCamelCase_ = special_tok_ids lowerCamelCase_ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f'''Loading data from {args.data_file}''' ) with open(args.data_file ,'rb' ) as fp: lowerCamelCase_ = pickle.load(__UpperCamelCase ) if args.mlm: logger.info(f'''Loading token counts from {args.token_counts} (already pre-computed)''' ) with open(args.token_counts ,'rb' ) as fp: lowerCamelCase_ = pickle.load(__UpperCamelCase ) lowerCamelCase_ = np.maximum(__UpperCamelCase ,1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): lowerCamelCase_ = 0.0 # do not predict special tokens lowerCamelCase_ = torch.from_numpy(__UpperCamelCase ) else: lowerCamelCase_ = None lowerCamelCase_ = LmSeqsDataset(params=__UpperCamelCase ,data=__UpperCamelCase ) logger.info('Data loader created.' ) # STUDENT # logger.info(f'''Loading student config from {args.student_config}''' ) lowerCamelCase_ = student_config_class.from_pretrained(args.student_config ) lowerCamelCase_ = True if args.student_pretrained_weights is not None: logger.info(f'''Loading pretrained weights from {args.student_pretrained_weights}''' ) lowerCamelCase_ = student_model_class.from_pretrained(args.student_pretrained_weights ,config=__UpperCamelCase ) else: lowerCamelCase_ = student_model_class(__UpperCamelCase ) if args.n_gpu > 0: student.to(f'''cuda:{args.local_rank}''' ) logger.info('Student loaded.' ) # TEACHER # lowerCamelCase_ = teacher_model_class.from_pretrained(args.teacher_name ,output_hidden_states=__UpperCamelCase ) if args.n_gpu > 0: teacher.to(f'''cuda:{args.local_rank}''' ) logger.info(f'''Teacher loaded from {args.teacher_name}.''' ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__UpperCamelCase ,__UpperCamelCase ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__UpperCamelCase ,__UpperCamelCase ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() lowerCamelCase_ = Distiller( params=__UpperCamelCase ,dataset=__UpperCamelCase ,token_probs=__UpperCamelCase ,student=__UpperCamelCase ,teacher=__UpperCamelCase ) distiller.train() logger.info('Let\'s go get some drinks.' ) if __name__ == "__main__": main()
42
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, 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 A_ = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A_ = 250_004 A_ = 250_020 @require_sentencepiece @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = MBartTokenizer SCREAMING_SNAKE_CASE_ = MBartTokenizerFast SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase_ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase_ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def UpperCamelCase( self ) -> int: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase_ = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCamelCase_ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) lowerCamelCase_ = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=True lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=False lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCamelCase_ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'facebook/mbart-large-en-ro' SCREAMING_SNAKE_CASE_ = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] SCREAMING_SNAKE_CASE_ = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] SCREAMING_SNAKE_CASE_ = [82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2, EN_CODE] @classmethod def UpperCamelCase( cls ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) lowerCamelCase_ = 1 return cls def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 250020 ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' self.assertIn(SCREAMING_SNAKE_CASE_ , self.tokenizer.all_special_ids ) lowerCamelCase_ = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] lowerCamelCase_ = self.tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 10 lowerCamelCase_ = self.tokenizer(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [250026, 250001] ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = MBartTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) lowerCamelCase_ = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) lowerCamelCase_ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer(self.src_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=3 , return_tensors='pt' ) lowerCamelCase_ = self.tokenizer( text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=10 , return_tensors='pt' ) lowerCamelCase_ = targets['input_ids'] lowerCamelCase_ = shift_tokens_right(SCREAMING_SNAKE_CASE_ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ) , { # A, test, EOS, en_XX 'input_ids': [[62, 3034, 2, 250004]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 250001, } , )
42
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A_ = { "configuration_efficientformer": [ "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ["EfficientFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientFormerForImageClassification", "EfficientFormerForImageClassificationWithTeacher", "EfficientFormerModel", "EfficientFormerPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFEfficientFormerForImageClassification", "TFEfficientFormerForImageClassificationWithTeacher", "TFEfficientFormerModel", "TFEfficientFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
42
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = 'ylacombe/bark-small' lowerCamelCase_ = tempfile.mkdtemp() lowerCamelCase_ = 'en_speaker_1' lowerCamelCase_ = 'This is a test string' lowerCamelCase_ = 'speaker_embeddings_path.json' lowerCamelCase_ = 'speaker_embeddings' def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase_ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase_ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCamelCase_ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='(BOS)' , eos_token='(EOS)' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase_ = 35 lowerCamelCase_ = 2 lowerCamelCase_ = 8 lowerCamelCase_ = { 'semantic_prompt': np.ones(SCREAMING_SNAKE_CASE_ ), 'coarse_prompt': np.ones((nb_codebooks_coarse, seq_len) ), 'fine_prompt': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() ) # test loading voice preset from npz file lowerCamelCase_ = os.path.join(self.tmpdirname , 'file.npz' ) np.savez(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() ) # test loading voice preset from the hub lowerCamelCase_ = processor(text=self.input_string , voice_preset=self.voice_preset ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = processor(text=self.input_string ) lowerCamelCase_ = tokenizer( self.input_string , padding='max_length' , max_length=256 , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
42
1
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase = 4_00_00_00 ) -> int: lowerCamelCase_ = [0, 1] lowerCamelCase_ = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 lowerCamelCase_ = 0 for j in range(len(__UpperCamelCase ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f'''{solution() = }''')
42
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} A_ = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } A_ = { "allenai/longformer-base-4096": 4_096, "allenai/longformer-large-4096": 4_096, "allenai/longformer-large-4096-finetuned-triviaqa": 4_096, "allenai/longformer-base-4096-extra.pos.embd.only": 4_096, "allenai/longformer-large-4096-extra.pos.embd.only": 4_096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _UpperCamelCase ( ) -> Any: lowerCamelCase_ = ( list(range(ord('!' ) ,ord('~' ) + 1 ) ) + list(range(ord('¡' ) ,ord('¬' ) + 1 ) ) + list(range(ord('®' ) ,ord('ÿ' ) + 1 ) ) ) lowerCamelCase_ = bs[:] lowerCamelCase_ = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 lowerCamelCase_ = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase ,__UpperCamelCase ) ) def _UpperCamelCase ( __UpperCamelCase ) -> List[str]: lowerCamelCase_ = set() lowerCamelCase_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCamelCase_ = char return pairs class UpperCAmelCase ( UpperCAmelCase__ ): '''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 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="replace" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else bos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else eos_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else sep_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else cls_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else unk_token lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase_ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( errors=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as vocab_handle: lowerCamelCase_ = json.load(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {v: k for k, v in self.encoder.items()} lowerCamelCase_ = errors # how to handle errors in decoding lowerCamelCase_ = bytes_to_unicode() lowerCamelCase_ = {v: k for k, v in self.byte_encoder.items()} with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as merges_handle: lowerCamelCase_ = merges_handle.read().split('\n' )[1:-1] lowerCamelCase_ = [tuple(merge.split() ) for merge in bpe_merges] lowerCamelCase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowerCamelCase_ = {} lowerCamelCase_ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowerCamelCase_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' return len(self.encoder ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' if token in self.cache: return self.cache[token] lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) if not pairs: return token while True: lowerCamelCase_ = min(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break lowerCamelCase_ ,lowerCamelCase_ = bigram lowerCamelCase_ = [] lowerCamelCase_ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): try: lowerCamelCase_ = word.index(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCamelCase_ = j if word[i] == first and i < len(SCREAMING_SNAKE_CASE_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCamelCase_ = tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = new_word if len(SCREAMING_SNAKE_CASE_ ) == 1: break else: lowerCamelCase_ = get_pairs(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = ' '.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = word return word def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' lowerCamelCase_ = [] for token in re.findall(self.pat , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(SCREAMING_SNAKE_CASE_ ).split(' ' ) ) return bpe_tokens def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' return self.encoder.get(SCREAMING_SNAKE_CASE_ , self.encoder.get(self.unk_token ) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' return self.decoder.get(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = ''.join(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) + '\n' ) lowerCamelCase_ = 0 with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ' Please check that the tokenizer is not corrupted!' ) lowerCamelCase_ = token_index writer.write(' '.join(SCREAMING_SNAKE_CASE_ ) + '\n' ) index += 1 return vocab_file, merge_file def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] lowerCamelCase_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' lowerCamelCase_ = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(SCREAMING_SNAKE_CASE_ ) > 0 and not text[0].isspace()): lowerCamelCase_ = ' ' + text return (text, kwargs)
42
1
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def _UpperCamelCase ( __UpperCamelCase ) -> List[Tuple[int, ...]]: lowerCamelCase_ = [] if isinstance(__UpperCamelCase ,__UpperCamelCase ): for v in tree.values(): shapes.extend(_fetch_dims(__UpperCamelCase ) ) elif isinstance(__UpperCamelCase ,(list, tuple) ): for t in tree: shapes.extend(_fetch_dims(__UpperCamelCase ) ) elif isinstance(__UpperCamelCase ,torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError('Not supported' ) return shapes @torch.jit.ignore def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Tuple[int, ...]: lowerCamelCase_ = [] for d in reversed(__UpperCamelCase ): idx.append(flat_idx % d ) lowerCamelCase_ = flat_idx // d return tuple(reversed(__UpperCamelCase ) ) @torch.jit.ignore def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase = None ,__UpperCamelCase = None ,) -> List[Tuple[slice, ...]]: # start_edges and end_edges both indicate whether, starting from any given # dimension, the start/end index is at the top/bottom edge of the # corresponding tensor, modeled as a tree def reduce_edge_list(__UpperCamelCase ) -> None: lowerCamelCase_ = True for i in range(len(__UpperCamelCase ) ): lowerCamelCase_ = -1 * (i + 1) l[reversed_idx] &= tally lowerCamelCase_ = l[reversed_idx] if start_edges is None: lowerCamelCase_ = [s == 0 for s in start] reduce_edge_list(__UpperCamelCase ) if end_edges is None: lowerCamelCase_ = [e == (d - 1) for e, d in zip(__UpperCamelCase ,__UpperCamelCase )] reduce_edge_list(__UpperCamelCase ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(__UpperCamelCase ) == 0: return [()] elif len(__UpperCamelCase ) == 1: return [(slice(start[0] ,end[0] + 1 ),)] lowerCamelCase_ = [] lowerCamelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(__UpperCamelCase ,__UpperCamelCase ): if s == e: path_list.append(slice(__UpperCamelCase ,s + 1 ) ) else: break lowerCamelCase_ = tuple(__UpperCamelCase ) lowerCamelCase_ = len(__UpperCamelCase ) # start == end, and we're done if divergence_idx == len(__UpperCamelCase ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowerCamelCase_ = start[divergence_idx] return tuple( path + (slice(__UpperCamelCase ,sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] ,[d - 1 for d in dims[divergence_idx + 1 :]] ,dims[divergence_idx + 1 :] ,start_edges=start_edges[divergence_idx + 1 :] ,end_edges=[True for _ in end_edges[divergence_idx + 1 :]] ,) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowerCamelCase_ = end[divergence_idx] return tuple( path + (slice(__UpperCamelCase ,edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] ,end[divergence_idx + 1 :] ,dims[divergence_idx + 1 :] ,start_edges=[True for _ in start_edges[divergence_idx + 1 :]] ,end_edges=end_edges[divergence_idx + 1 :] ,) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] ,end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] ,end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 ,end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) lowerCamelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 ,end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> torch.Tensor: lowerCamelCase_ = t.shape[:no_batch_dims] lowerCamelCase_ = list(_flat_idx_to_idx(__UpperCamelCase ,__UpperCamelCase ) ) # _get_minimal_slice_set is inclusive lowerCamelCase_ = list(_flat_idx_to_idx(flat_end - 1 ,__UpperCamelCase ) ) # Get an ordered list of slices to perform lowerCamelCase_ = _get_minimal_slice_set( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,) lowerCamelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase = False ,__UpperCamelCase = None ,__UpperCamelCase = False ,) -> Any: if not (len(__UpperCamelCase ) > 0): raise ValueError('Must provide at least one input' ) lowerCamelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(__UpperCamelCase )] lowerCamelCase_ = tuple([max(__UpperCamelCase ) for s in zip(*__UpperCamelCase )] ) def _prep_inputs(__UpperCamelCase ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: lowerCamelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) lowerCamelCase_ = t.reshape(-1 ,*t.shape[no_batch_dims:] ) else: lowerCamelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t lowerCamelCase_ = tensor_tree_map(_prep_inputs ,__UpperCamelCase ) lowerCamelCase_ = None if _out is not None: lowerCamelCase_ = tensor_tree_map(lambda __UpperCamelCase : t.view([-1] + list(t.shape[no_batch_dims:] ) ) ,_out ) lowerCamelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d lowerCamelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(__UpperCamelCase ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t lowerCamelCase_ = 0 lowerCamelCase_ = prepped_outputs for _ in range(__UpperCamelCase ): # Chunk the input if not low_mem: lowerCamelCase_ = _select_chunk else: lowerCamelCase_ = partial( _chunk_slice ,flat_start=__UpperCamelCase ,flat_end=min(__UpperCamelCase ,i + chunk_size ) ,no_batch_dims=len(__UpperCamelCase ) ,) lowerCamelCase_ = tensor_tree_map(__UpperCamelCase ,__UpperCamelCase ) # Run the layer on the chunk lowerCamelCase_ = layer(**__UpperCamelCase ) # Allocate space for the output if out is None: lowerCamelCase_ = tensor_tree_map(lambda __UpperCamelCase : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) ,__UpperCamelCase ) # Put the chunk in its pre-allocated space if isinstance(__UpperCamelCase ,__UpperCamelCase ): def assign(__UpperCamelCase ,__UpperCamelCase ) -> None: for k, v in da.items(): if isinstance(__UpperCamelCase ,__UpperCamelCase ): assign(__UpperCamelCase ,da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: lowerCamelCase_ = da[k] assign(__UpperCamelCase ,__UpperCamelCase ) elif isinstance(__UpperCamelCase ,__UpperCamelCase ): for xa, xa in zip(__UpperCamelCase ,__UpperCamelCase ): if _add_into_out: xa[i : i + chunk_size] += xa else: lowerCamelCase_ = xa elif isinstance(__UpperCamelCase ,torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: lowerCamelCase_ = output_chunk else: raise ValueError('Not supported' ) i += chunk_size lowerCamelCase_ = tensor_tree_map(lambda __UpperCamelCase : t.view(orig_batch_dims + t.shape[1:] ) ,__UpperCamelCase ) return out class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ = 512 , ) -> int: '''simple docstring''' lowerCamelCase_ = max_chunk_size lowerCamelCase_ = None lowerCamelCase_ = None def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' logging.info('Tuning chunk size...' ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size lowerCamelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] lowerCamelCase_ = [c for c in candidates if c > min_chunk_size] lowerCamelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(SCREAMING_SNAKE_CASE_ ) -> bool: try: with torch.no_grad(): fn(*SCREAMING_SNAKE_CASE_ , chunk_size=SCREAMING_SNAKE_CASE_ ) return True except RuntimeError: return False lowerCamelCase_ = 0 lowerCamelCase_ = len(SCREAMING_SNAKE_CASE_ ) - 1 while i > min_viable_chunk_size_index: lowerCamelCase_ = test_chunk_size(candidates[i] ) if not viable: lowerCamelCase_ = (min_viable_chunk_size_index + i) // 2 else: lowerCamelCase_ = i lowerCamelCase_ = (i + len(SCREAMING_SNAKE_CASE_ ) - 1) // 2 return candidates[min_viable_chunk_size_index] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> bool: '''simple docstring''' lowerCamelCase_ = True for aa, aa in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): assert type(SCREAMING_SNAKE_CASE_ ) == type(SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ): consistent &= self._compare_arg_caches(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [v for _, v in sorted(aa.items() , key=lambda SCREAMING_SNAKE_CASE_ : x[0] )] lowerCamelCase_ = [v for _, v in sorted(aa.items() , key=lambda SCREAMING_SNAKE_CASE_ : x[0] )] consistent &= self._compare_arg_caches(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: consistent &= aa == aa return consistent def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> int: '''simple docstring''' lowerCamelCase_ = True lowerCamelCase_ = tree_map(lambda SCREAMING_SNAKE_CASE_ : a.shape if isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) else a , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self._compare_arg_caches(self.cached_arg_data , SCREAMING_SNAKE_CASE_ ) else: # Otherwise, we can reuse the precomputed value lowerCamelCase_ = False if not consistent: lowerCamelCase_ = self._determine_favorable_chunk_size( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
42
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer A_ = logging.get_logger(__name__) A_ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} A_ = { "vocab_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt" ), "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt", "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt", "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt", "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt", }, "tokenizer_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json" ), "google/realm-orqa-nq-openqa": ( "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-nq-reader": ( "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-openqa": ( "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-reader": ( "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json" ), }, } A_ = { "google/realm-cc-news-pretrained-embedder": 512, "google/realm-cc-news-pretrained-encoder": 512, "google/realm-cc-news-pretrained-scorer": 512, "google/realm-cc-news-pretrained-openqa": 512, "google/realm-orqa-nq-openqa": 512, "google/realm-orqa-nq-reader": 512, "google/realm-orqa-wq-openqa": 512, "google/realm-orqa-wq-reader": 512, } A_ = { "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-reader": {"do_lower_case": True}, "google/realm-orqa-wq-openqa": {"do_lower_case": True}, "google/realm-orqa-wq-reader": {"do_lower_case": True}, } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ = RealmTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="[UNK]" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="[PAD]" , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[MASK]" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> List[Any]: '''simple docstring''' super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , do_lower_case=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , SCREAMING_SNAKE_CASE_ ) != do_lower_case or normalizer_state.get('strip_accents' , SCREAMING_SNAKE_CASE_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , SCREAMING_SNAKE_CASE_ ) != tokenize_chinese_chars ): lowerCamelCase_ = getattr(SCREAMING_SNAKE_CASE_ , normalizer_state.pop('type' ) ) lowerCamelCase_ = do_lower_case lowerCamelCase_ = strip_accents lowerCamelCase_ = tokenize_chinese_chars lowerCamelCase_ = normalizer_class(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = do_lower_case def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = PaddingStrategy.MAX_LENGTH lowerCamelCase_ = text lowerCamelCase_ = kwargs.pop('text_pair' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = kwargs.pop('return_tensors' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = { 'input_ids': [], 'attention_mask': [], 'token_type_ids': [], } for idx, candidate_text in enumerate(SCREAMING_SNAKE_CASE_ ): if batch_text_pair is not None: lowerCamelCase_ = batch_text_pair[idx] else: lowerCamelCase_ = None lowerCamelCase_ = super().__call__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = encoded_candidates.get('input_ids' ) lowerCamelCase_ = encoded_candidates.get('attention_mask' ) lowerCamelCase_ = encoded_candidates.get('token_type_ids' ) if encoded_input_ids is not None: output_data["input_ids"].append(SCREAMING_SNAKE_CASE_ ) if encoded_attention_mask is not None: output_data["attention_mask"].append(SCREAMING_SNAKE_CASE_ ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = {key: item for key, item in output_data.items() if len(SCREAMING_SNAKE_CASE_ ) != 0} return BatchEncoding(SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: '''simple docstring''' lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: '''simple docstring''' lowerCamelCase_ = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
42
1
'''simple docstring''' import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def _UpperCamelCase ( __UpperCamelCase ) -> str: lowerCamelCase_ = [] for line in lines: lowerCamelCase_ = re.sub(R'#.*' ,'' ,__UpperCamelCase ) # remove comments if line: filtered_lines.append(__UpperCamelCase ) lowerCamelCase_ = '\n'.join(__UpperCamelCase ) # Make a hash from all this code lowerCamelCase_ = full_str.encode('utf-8' ) return shaaaa(__UpperCamelCase ).hexdigest() # get importable module names and hash for caching A_ = { "csv": (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), "json": (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), "pandas": (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), "parquet": (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), "arrow": (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), "text": (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), "imagefolder": (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), "audiofolder": (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions A_ = { ".csv": ("csv", {}), ".tsv": ("csv", {"sep": "\t"}), ".json": ("json", {}), ".jsonl": ("json", {}), ".parquet": ("parquet", {}), ".arrow": ("arrow", {}), ".txt": ("text", {}), } _EXTENSION_TO_MODULE.update({ext: ("imagefolder", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("imagefolder", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ("audiofolder", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("audiofolder", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) A_ = {"imagefolder", "audiofolder"} # Used to filter data files based on extensions given a module name A_ = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append(".zip") _MODULE_TO_EXTENSIONS["audiofolder"].append(".zip")
42
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __UpperCamelCase ) -> bool: lowerCamelCase_ = str(__UpperCamelCase ) return len(__UpperCamelCase ) == 9 and set(__UpperCamelCase ) == set('123456789' ) def _UpperCamelCase ( ) -> int | None: for base_num in range(99_99 ,49_99 ,-1 ): lowerCamelCase_ = 10_00_02 * base_num if is_9_pandigital(__UpperCamelCase ): return candidate for base_num in range(3_33 ,99 ,-1 ): lowerCamelCase_ = 1_00_20_03 * base_num if is_9_pandigital(__UpperCamelCase ): return candidate return None if __name__ == "__main__": print(f'''{solution() = }''')
42
1
'''simple docstring''' import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration A_ = 500_000 A_ , A_ = os.path.split(__file__) A_ = os.path.join(RESULTS_BASEPATH, "results", RESULTS_FILENAME.replace(".py", ".json")) @get_duration def _UpperCamelCase ( __UpperCamelCase ,**__UpperCamelCase ) -> int: lowerCamelCase_ = dataset.map(**__UpperCamelCase ) @get_duration def _UpperCamelCase ( __UpperCamelCase ,**__UpperCamelCase ) -> Any: lowerCamelCase_ = dataset.filter(**__UpperCamelCase ) def _UpperCamelCase ( ) -> List[str]: lowerCamelCase_ = {'num examples': SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase_ = datasets.Features({'text': datasets.Value('string' ), 'numbers': datasets.Value('float32' )} ) lowerCamelCase_ = generate_example_dataset( os.path.join(__UpperCamelCase ,'dataset.arrow' ) ,__UpperCamelCase ,num_examples=__UpperCamelCase ) lowerCamelCase_ = transformers.AutoTokenizer.from_pretrained('bert-base-cased' ,use_fast=__UpperCamelCase ) def tokenize(__UpperCamelCase ): return tokenizer(examples['text'] ) lowerCamelCase_ = map(__UpperCamelCase ) lowerCamelCase_ = map(__UpperCamelCase ,batched=__UpperCamelCase ) lowerCamelCase_ = map(__UpperCamelCase ,function=lambda __UpperCamelCase : None ,batched=__UpperCamelCase ) with dataset.formatted_as(type='numpy' ): lowerCamelCase_ = map(__UpperCamelCase ,function=lambda __UpperCamelCase : None ,batched=__UpperCamelCase ) with dataset.formatted_as(type='pandas' ): lowerCamelCase_ = map(__UpperCamelCase ,function=lambda __UpperCamelCase : None ,batched=__UpperCamelCase ) with dataset.formatted_as(type='torch' ,columns='numbers' ): lowerCamelCase_ = map(__UpperCamelCase ,function=lambda __UpperCamelCase : None ,batched=__UpperCamelCase ) with dataset.formatted_as(type='tensorflow' ,columns='numbers' ): lowerCamelCase_ = map(__UpperCamelCase ,function=lambda __UpperCamelCase : None ,batched=__UpperCamelCase ) lowerCamelCase_ = map(__UpperCamelCase ,function=__UpperCamelCase ,batched=__UpperCamelCase ) lowerCamelCase_ = filter(__UpperCamelCase ) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(__UpperCamelCase ,'wb' ) as f: f.write(json.dumps(__UpperCamelCase ).encode('utf-8' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
42
'''simple docstring''' A_ = "Input must be a string of 8 numbers plus letter" A_ = "TRWAGMYFPDXBNJZSQVHLCKE" def _UpperCamelCase ( __UpperCamelCase ) -> bool: if not isinstance(__UpperCamelCase ,__UpperCamelCase ): lowerCamelCase_ = f'''Expected string as input, found {type(__UpperCamelCase ).__name__}''' raise TypeError(__UpperCamelCase ) lowerCamelCase_ = spanish_id.replace('-' ,'' ).upper() if len(__UpperCamelCase ) != 9: raise ValueError(__UpperCamelCase ) try: lowerCamelCase_ = int(spanish_id_clean[0:8] ) lowerCamelCase_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(__UpperCamelCase ) from ex if letter.isdigit(): raise ValueError(__UpperCamelCase ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
42
1
'''simple docstring''' from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
42
'''simple docstring''' import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = GPTSanJapaneseTokenizer SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = {'do_clean_text': False, 'add_prefix_space': False} def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' super().setUp() # fmt: off lowerCamelCase_ = ['こん', 'こんに', 'にちは', 'ばんは', '世界,㔺界', '、', '。', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on lowerCamelCase_ = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # 😀 lowerCamelCase_ = {'unk_token': '<unk>'} lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。 \nこんばんは、世界。😀' return input_text, output_text def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = self.get_input_output_texts(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ ) return text, ids def UpperCamelCase( self ) -> Tuple: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass # TODO add if relevant def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。 こんばんは、㔺界。' lowerCamelCase_ = ['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。'] lowerCamelCase_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids without special tokens lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing conversion to ids with special tokens lowerCamelCase_ = tokens + [tokenizer.unk_token] lowerCamelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] lowerCamelCase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.get_tokenizer() # Testing tokenization lowerCamelCase_ = 'こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。' lowerCamelCase_ = 'こんにちは、、、、世界。こんばんは、、、、世界。' lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = 'こんにちは、世界。こんばんは、世界。😀' lowerCamelCase_ = tokenizer.encode(prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode('' , prefix_text=prefix_text + input_text ) lowerCamelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization lowerCamelCase_ = 'こんにちは、世界。' lowerCamelCase_ = 'こんばんは、㔺界。😀' lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = len(tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) - 2 lowerCamelCase_ = [1] + [0] * (len_prefix + len_text + 1) lowerCamelCase_ = [1] * (len_prefix + len_text + 1) + [0] lowerCamelCase_ = [1] + [1] * (len_prefix) + [0] * (len_text + 1) lowerCamelCase_ = tokenizer(prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , prefix_text=SCREAMING_SNAKE_CASE_ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = tokenizer.encode('あンいワ' ) lowerCamelCase_ = tokenizer.encode('' , prefix_text='あンいワ' ) lowerCamelCase_ = tokenizer.encode('いワ' , prefix_text='あン' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE_ ) , tokenizer.decode(SCREAMING_SNAKE_CASE_ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) lowerCamelCase_ = [['武田信玄', 'は、'], ['織田信長', 'の配下の、']] lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) # fmt: off lowerCamelCase_ = [[35993, 8640, 25948, 35998, 30647, 35675, 35999, 35999], [35993, 10382, 9868, 35998, 30646, 9459, 30646, 35675]] lowerCamelCase_ = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] lowerCamelCase_ = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass
42
1
'''simple docstring''' from __future__ import annotations from typing import Any def _UpperCamelCase ( __UpperCamelCase ) -> None: create_state_space_tree(__UpperCamelCase ,[] ,0 ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> None: if index == len(__UpperCamelCase ): print(__UpperCamelCase ) return create_state_space_tree(__UpperCamelCase ,__UpperCamelCase ,index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(__UpperCamelCase ,__UpperCamelCase ,index + 1 ) current_subsequence.pop() if __name__ == "__main__": A_ = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
42
'''simple docstring''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Dict: '''simple docstring''' super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> List[str]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory lowerCamelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> List[str]: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}''' ) 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 (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(SCREAMING_SNAKE_CASE_ )}.''' ) # get prompt text embeddings lowerCamelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=self.tokenizer.model_max_length , return_tensors='pt' , ) lowerCamelCase_ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowerCamelCase_ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( 'The following part of your input was truncated because CLIP can only handle sequences up to' f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) lowerCamelCase_ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: lowerCamelCase_ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = text_embeddings.shape lowerCamelCase_ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) lowerCamelCase_ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # 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. lowerCamelCase_ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: lowerCamelCase_ = 42 if negative_prompt is None: lowerCamelCase_ = [''] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( f'''`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=''' f''' {type(SCREAMING_SNAKE_CASE_ )}.''' ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( f'''`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:''' f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' ' the batch size of `prompt`.' ) else: lowerCamelCase_ = negative_prompt lowerCamelCase_ = text_input_ids.shape[-1] lowerCamelCase_ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='pt' , ) lowerCamelCase_ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCamelCase_ = uncond_embeddings.shape[1] lowerCamelCase_ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) lowerCamelCase_ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCamelCase_ = 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`. lowerCamelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) lowerCamelCase_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) lowerCamelCase_ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps lowerCamelCase_ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='cpu' , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) lowerCamelCase_ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='cpu' , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: lowerCamelCase_ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) lowerCamelCase_ = latents_reference.to(self.device ) lowerCamelCase_ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images lowerCamelCase_ = (latents_shape[3] - latents_shape_reference[3]) // 2 lowerCamelCase_ = (latents_shape[2] - latents_shape_reference[2]) // 2 lowerCamelCase_ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx lowerCamelCase_ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy lowerCamelCase_ = 0 if dx < 0 else dx lowerCamelCase_ = 0 if dy < 0 else dy lowerCamelCase_ = max(-dx , 0 ) lowerCamelCase_ = max(-dy , 0 ) # import pdb # pdb.set_trace() lowerCamelCase_ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand lowerCamelCase_ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowerCamelCase_ = 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] lowerCamelCase_ = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowerCamelCase_ = {} if accepts_eta: lowerCamelCase_ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance lowerCamelCase_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCamelCase_ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual lowerCamelCase_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: lowerCamelCase_ ,lowerCamelCase_ = noise_pred.chunk(2 ) lowerCamelCase_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 1 / 0.18_215 * latents lowerCamelCase_ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample lowerCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: lowerCamelCase_ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors='pt' ).to( self.device ) lowerCamelCase_ ,lowerCamelCase_ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: lowerCamelCase_ = None if output_type == "pil": lowerCamelCase_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
42
1
'''simple docstring''' from PIL import Image def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Image: def brightness(__UpperCamelCase ) -> float: return 1_28 + level + (c - 1_28) if not -255.0 <= level <= 255.0: raise ValueError('level must be between -255.0 (black) and 255.0 (white)' ) return img.point(__UpperCamelCase ) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change brightness to 100 A_ = change_brightness(img, 100) brigt_img.save("image_data/lena_brightness.png", format="png")
42
'''simple docstring''' import pprint import requests A_ = "https://zenquotes.io/api" def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/today' ).json() def _UpperCamelCase ( ) -> list: return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": A_ = random_quotes() pprint.pprint(response)
42
1
'''simple docstring''' from __future__ import annotations from math import pow, sqrt def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> dict[str, float]: if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if resistance == 0: return {"resistance": sqrt(pow(__UpperCamelCase ,2 ) - pow(__UpperCamelCase ,2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(__UpperCamelCase ,2 ) - pow(__UpperCamelCase ,2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(__UpperCamelCase ,2 ) + pow(__UpperCamelCase ,2 ) )} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
42
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=33 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ) -> int: '''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_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = num_attention_heads lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = type_vocab_size lowerCamelCase_ = type_sequence_label_size lowerCamelCase_ = initializer_range lowerCamelCase_ = num_labels lowerCamelCase_ = num_choices lowerCamelCase_ = scope def UpperCamelCase( self ) -> str: '''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 lowerCamelCase_ = None lowerCamelCase_ = None if self.use_labels: lowerCamelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase_ = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase_ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase( self ) -> List[str]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 , ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = EsmModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = EsmForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: '''simple docstring''' lowerCamelCase_ = self.num_labels lowerCamelCase_ = EsmForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) ,( lowerCamelCase_ ) , ) = config_and_inputs lowerCamelCase_ = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ = () SCREAMING_SNAKE_CASE_ = ( { 'feature-extraction': EsmModel, 'fill-mask': EsmForMaskedLM, 'text-classification': EsmForSequenceClassification, 'token-classification': EsmForTokenClassification, 'zero-shot': EsmForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = EsmModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> str: '''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(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> int: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ = EsmModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()[0] lowerCamelCase_ = EsmEmbeddings(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) lowerCamelCase_ = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) lowerCamelCase_ = create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE_ , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()[0] lowerCamelCase_ = EsmEmbeddings(config=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.empty(2 , 4 , 30 ) lowerCamelCase_ = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] lowerCamelCase_ = torch.as_tensor([expected_single_positions, expected_single_positions] ) lowerCamelCase_ = embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE_ ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) @unittest.skip('Esm does not support embedding resizing' ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' pass @unittest.skip('Esm does not support embedding resizing' ) def UpperCamelCase( self ) -> Any: '''simple docstring''' pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' pass @require_torch class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' with torch.no_grad(): lowerCamelCase_ = EsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() lowerCamelCase_ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )[0] lowerCamelCase_ = 33 lowerCamelCase_ = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCamelCase( self ) -> Tuple: '''simple docstring''' with torch.no_grad(): lowerCamelCase_ = EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() lowerCamelCase_ = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ )[0] # compare the actual values for a slice. lowerCamelCase_ = torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
42
1
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "asapp/sew-d-tiny-100k": "https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json", # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'sew-d' def __init__( self , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=("p2c", "c2p") , SCREAMING_SNAKE_CASE_="layer_norm" , SCREAMING_SNAKE_CASE_="gelu_python" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1E-7 , SCREAMING_SNAKE_CASE_=1E-5 , SCREAMING_SNAKE_CASE_="group" , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , SCREAMING_SNAKE_CASE_=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE_=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=128 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0.05 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_="mean" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , ) -> Optional[int]: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = hidden_size lowerCamelCase_ = feat_extract_norm lowerCamelCase_ = feat_extract_activation lowerCamelCase_ = list(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = list(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = list(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = conv_bias lowerCamelCase_ = num_conv_pos_embeddings lowerCamelCase_ = num_conv_pos_embedding_groups lowerCamelCase_ = len(self.conv_dim ) lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = intermediate_size lowerCamelCase_ = squeeze_factor lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = position_buckets lowerCamelCase_ = share_att_key lowerCamelCase_ = relative_attention lowerCamelCase_ = norm_rel_ebd lowerCamelCase_ = list(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = hidden_act lowerCamelCase_ = num_attention_heads lowerCamelCase_ = hidden_dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = feat_proj_dropout lowerCamelCase_ = final_dropout lowerCamelCase_ = layer_norm_eps lowerCamelCase_ = feature_layer_norm_eps lowerCamelCase_ = initializer_range lowerCamelCase_ = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowerCamelCase_ = apply_spec_augment lowerCamelCase_ = mask_time_prob lowerCamelCase_ = mask_time_length lowerCamelCase_ = mask_time_min_masks lowerCamelCase_ = mask_feature_prob lowerCamelCase_ = mask_feature_length lowerCamelCase_ = mask_feature_min_masks # ctc loss lowerCamelCase_ = ctc_loss_reduction lowerCamelCase_ = ctc_zero_infinity # sequence classification lowerCamelCase_ = use_weighted_layer_sum lowerCamelCase_ = classifier_proj_size @property def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
42
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A_ = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
42
1
'''simple docstring''' import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = LEDTokenizer SCREAMING_SNAKE_CASE_ = LEDTokenizerFast SCREAMING_SNAKE_CASE_ = True def UpperCamelCase( self ) -> str: '''simple docstring''' super().setUp() lowerCamelCase_ = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] lowerCamelCase_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) lowerCamelCase_ = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] lowerCamelCase_ = {'unk_token': '<unk>'} lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: '''simple docstring''' return "lower newer", "lower newer" @cached_property def UpperCamelCase( self ) -> str: '''simple docstring''' return LEDTokenizer.from_pretrained('allenai/led-base-16384' ) @cached_property def UpperCamelCase( self ) -> Any: '''simple docstring''' return LEDTokenizerFast.from_pretrained('allenai/led-base-16384' ) @require_torch def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] lowerCamelCase_ = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , max_length=len(SCREAMING_SNAKE_CASE_ ) , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) lowerCamelCase_ = batch.input_ids.tolist()[0] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) self.assertIn('input_ids' , SCREAMING_SNAKE_CASE_ ) self.assertIn('attention_mask' , SCREAMING_SNAKE_CASE_ ) self.assertNotIn('labels' , SCREAMING_SNAKE_CASE_ ) self.assertNotIn('decoder_attention_mask' , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = [ 'Summary of the text.', 'Another summary.', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase_ = tokenizer(text_target=SCREAMING_SNAKE_CASE_ , max_length=32 , padding='max_length' , return_tensors='pt' ) self.assertEqual(32 , targets['input_ids'].shape[1] ) @require_torch def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase_ = tokenizer( ['I am a small frog' * 1024, 'I am a small frog'] , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(batch.input_ids.shape , (2, 5122) ) @require_torch def UpperCamelCase( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase_ = ['A long paragraph for summarization.'] lowerCamelCase_ = [ 'Summary of the text.', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) lowerCamelCase_ = tokenizer(text_target=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) lowerCamelCase_ = inputs['input_ids'] lowerCamelCase_ = targets['input_ids'] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def UpperCamelCase( self ) -> Tuple: '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: lowerCamelCase_ = ['Summary of the text.', 'Another summary.'] lowerCamelCase_ = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = [[0] * len(SCREAMING_SNAKE_CASE_ ) for x in encoded_output['input_ids']] lowerCamelCase_ = tokenizer.pad(SCREAMING_SNAKE_CASE_ ) self.assertSequenceEqual(outputs['global_attention_mask'] , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' pass def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCamelCase_ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = 'A, <mask> AllenNLP sentence.' lowerCamelCase_ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) self.assertEqual(sum(tokens_r['token_type_ids'] ) , sum(tokens_p['token_type_ids'] ) ) self.assertEqual( sum(tokens_r['attention_mask'] ) / len(tokens_r['attention_mask'] ) , sum(tokens_p['attention_mask'] ) / len(tokens_p['attention_mask'] ) , ) lowerCamelCase_ = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] ) lowerCamelCase_ = tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] ) self.assertSequenceEqual(tokens_p['input_ids'] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r['input_ids'] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )
42
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json" ), } class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 'xlm-prophetnet' SCREAMING_SNAKE_CASE_ = ['past_key_values'] SCREAMING_SNAKE_CASE_ = { 'num_attention_heads': 'num_encoder_attention_heads', } def __init__( self , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = "gelu" , SCREAMING_SNAKE_CASE_ = 30522 , SCREAMING_SNAKE_CASE_ = 1024 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 4096 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 2 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 128 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 2 , **SCREAMING_SNAKE_CASE_ , ) -> Tuple: '''simple docstring''' lowerCamelCase_ = vocab_size lowerCamelCase_ = hidden_size lowerCamelCase_ = encoder_ffn_dim lowerCamelCase_ = num_encoder_layers lowerCamelCase_ = num_encoder_attention_heads lowerCamelCase_ = decoder_ffn_dim lowerCamelCase_ = num_decoder_layers lowerCamelCase_ = num_decoder_attention_heads lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = init_std # Normal(0, this parameter) lowerCamelCase_ = activation_function # parameters for xlmprophetnet lowerCamelCase_ = ngram lowerCamelCase_ = num_buckets lowerCamelCase_ = relative_max_distance lowerCamelCase_ = disable_ngram_loss lowerCamelCase_ = eps # 3 Types of Dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = dropout lowerCamelCase_ = use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , add_cross_attention=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @property def UpperCamelCase( self ) -> int: '''simple docstring''' return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' raise NotImplementedError( 'This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and' ' `num_decoder_layers`.' )
42
1
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> bool: lowerCamelCase_ = get_failure_array(__UpperCamelCase ) # 2) Step through text searching for pattern lowerCamelCase_ ,lowerCamelCase_ = 0, 0 # index into text, pattern while i < len(__UpperCamelCase ): if pattern[j] == text[i]: if j == (len(__UpperCamelCase ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: lowerCamelCase_ = failure[j - 1] continue i += 1 return False def _UpperCamelCase ( __UpperCamelCase ) -> list[int]: lowerCamelCase_ = [0] lowerCamelCase_ = 0 lowerCamelCase_ = 1 while j < len(__UpperCamelCase ): if pattern[i] == pattern[j]: i += 1 elif i > 0: lowerCamelCase_ = failure[i - 1] continue j += 1 failure.append(__UpperCamelCase ) return failure if __name__ == "__main__": # Test 1) A_ = "abc1abc12" A_ = "alskfjaldsabc1abc1abc12k23adsfabcabc" A_ = "alskfjaldsk23adsfabcabc" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) A_ = "ABABX" A_ = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) A_ = "AAAB" A_ = "ABAAAAAB" assert kmp(pattern, text) # Test 4) A_ = "abcdabcy" A_ = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) A_ = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
42
'''simple docstring''' import colorsys from PIL import Image # type: ignore def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> float: lowerCamelCase_ = x lowerCamelCase_ = y for step in range(__UpperCamelCase ): # noqa: B007 lowerCamelCase_ = a * a - b * b + x lowerCamelCase_ = 2 * a * b + y lowerCamelCase_ = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _UpperCamelCase ( __UpperCamelCase ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _UpperCamelCase ( __UpperCamelCase ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(__UpperCamelCase ,1 ,1 ) ) def _UpperCamelCase ( __UpperCamelCase = 8_00 ,__UpperCamelCase = 6_00 ,__UpperCamelCase = -0.6 ,__UpperCamelCase = 0 ,__UpperCamelCase = 3.2 ,__UpperCamelCase = 50 ,__UpperCamelCase = True ,) -> Image.Image: lowerCamelCase_ = Image.new('RGB' ,(image_width, image_height) ) lowerCamelCase_ = img.load() # loop through the image-coordinates for image_x in range(__UpperCamelCase ): for image_y in range(__UpperCamelCase ): # determine the figure-coordinates based on the image-coordinates lowerCamelCase_ = figure_width / image_width * image_height lowerCamelCase_ = figure_center_x + (image_x / image_width - 0.5) * figure_width lowerCamelCase_ = figure_center_y + (image_y / image_height - 0.5) * figure_height lowerCamelCase_ = get_distance(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: lowerCamelCase_ = get_color_coded_rgb(__UpperCamelCase ) else: lowerCamelCase_ = get_black_and_white_rgb(__UpperCamelCase ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure A_ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
42
1
'''simple docstring''' from collections.abc import Callable class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ = None ) -> None: '''simple docstring''' lowerCamelCase_ = [] # Stores indexes of each item for supporting updates and deletion. lowerCamelCase_ = {} # Stores current size of heap. lowerCamelCase_ = 0 # Stores function used to evaluate the score of an item on which basis ordering # will be done. lowerCamelCase_ = key or (lambda SCREAMING_SNAKE_CASE_ : x) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int | None: '''simple docstring''' return int((i - 1) / 2 ) if i > 0 else None def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int | None: '''simple docstring''' lowerCamelCase_ = int(2 * i + 1 ) return left if 0 < left < self.size else None def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int | None: '''simple docstring''' lowerCamelCase_ = int(2 * i + 2 ) return right if 0 < right < self.size else None def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None: '''simple docstring''' lowerCamelCase_ ,lowerCamelCase_ = ( self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]], ) # Then swap the items in the list. lowerCamelCase_ ,lowerCamelCase_ = self.arr[j], self.arr[i] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> bool: '''simple docstring''' return self.arr[i][1] < self.arr[j][1] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> int: '''simple docstring''' lowerCamelCase_ = self._left(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self._right(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = i if left is not None and not self._cmp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = left if right is not None and not self._cmp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = right return valid_parent def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> None: '''simple docstring''' lowerCamelCase_ = self._parent(SCREAMING_SNAKE_CASE_ ) while parent is not None and not self._cmp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self._swap(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ ,lowerCamelCase_ = parent, self._parent(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> None: '''simple docstring''' lowerCamelCase_ = self._get_valid_parent(SCREAMING_SNAKE_CASE_ ) while valid_parent != index: self._swap(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ ,lowerCamelCase_ = valid_parent, self._get_valid_parent(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None: '''simple docstring''' if item not in self.pos_map: return lowerCamelCase_ = self.pos_map[item] lowerCamelCase_ = [item, self.key(SCREAMING_SNAKE_CASE_ )] # Make sure heap is right in both up and down direction. # Ideally only one of them will make any change. self._heapify_up(SCREAMING_SNAKE_CASE_ ) self._heapify_down(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> None: '''simple docstring''' if item not in self.pos_map: return lowerCamelCase_ = self.pos_map[item] del self.pos_map[item] lowerCamelCase_ = self.arr[self.size - 1] lowerCamelCase_ = index self.size -= 1 # Make sure heap is right in both up and down direction. Ideally only one # of them will make any change- so no performance loss in calling both. if self.size > index: self._heapify_up(SCREAMING_SNAKE_CASE_ ) self._heapify_down(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None: '''simple docstring''' lowerCamelCase_ = len(self.arr ) if arr_len == self.size: self.arr.append([item, self.key(SCREAMING_SNAKE_CASE_ )] ) else: lowerCamelCase_ = [item, self.key(SCREAMING_SNAKE_CASE_ )] lowerCamelCase_ = self.size self.size += 1 self._heapify_up(self.size - 1 ) def UpperCamelCase( self ) -> tuple | None: '''simple docstring''' return self.arr[0] if self.size else None def UpperCamelCase( self ) -> tuple | None: '''simple docstring''' lowerCamelCase_ = self.get_top() if top_item_tuple: self.delete_item(top_item_tuple[0] ) return top_item_tuple def _UpperCamelCase ( ) -> None: pass if __name__ == "__main__": import doctest doctest.testmod()
42
'''simple docstring''' from math import isclose, sqrt def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> tuple[float, float, float]: lowerCamelCase_ = point_y / 4 / point_x lowerCamelCase_ = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) lowerCamelCase_ = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) lowerCamelCase_ = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 lowerCamelCase_ = outgoing_gradient**2 + 4 lowerCamelCase_ = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) lowerCamelCase_ = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 lowerCamelCase_ = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) lowerCamelCase_ = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point lowerCamelCase_ = x_minus if isclose(__UpperCamelCase ,__UpperCamelCase ) else x_plus lowerCamelCase_ = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _UpperCamelCase ( __UpperCamelCase = 1.4 ,__UpperCamelCase = -9.6 ) -> int: lowerCamelCase_ = 0 lowerCamelCase_ = first_x_coord lowerCamelCase_ = first_y_coord lowerCamelCase_ = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = next_point(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
42
1