code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int ) -> Dict: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer __a = flax_key_tuple[:-1] + ('''weight''',) __a = torch.permute(lowerCAmelCase__ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(lowerCAmelCase__ ): # linear layer __a = flax_key_tuple[:-1] + ('''weight''',) __a = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: __a = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict ) -> str: if "metadata" in layer: __a = layer.split('''metadata''' ) __a = ''''''.join(split_layer[0] )[:-1] __a = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )] elif "kvstore" in layer: __a = layer.split('''kvstore''' ) __a = ''''''.join(split_layer[0] )[:-1] __a = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )] else: __a = layer.split('''/''' ) __a = '''/'''.join(split_layer[:-1] ) __a = (split_layer[-1],) if "kvstore/path" in layer: __a = f'''{switch_checkpoint_path}/{checkpoint_info[layer]}''' elif "kvstore/driver" in layer: __a = '''file''' else: __a = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = rename_keys(lowerCAmelCase__ ) __a = {} for k, v in current_block.items(): __a = v __a = new_current_block torch.save(lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : int , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str = WEIGHTS_NAME ) -> Optional[Any]: __a = convert_file_size_to_int(lowerCAmelCase__ ) __a = [] __a = {} __a = 0 __a = 0 os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) with gfile.GFile(switch_checkpoint_path + '''/checkpoint''' , '''rb''' ) as fp: __a = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] __a = flatten_dict(lowerCAmelCase__ , sep='''/''' ) __a = {} for layer in checkpoint_info.keys(): __a , __a , __a = get_key_and_tensorstore_dict( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if curr_real_layer_name in all_layers: __a = content else: __a = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file __a = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() __a = torch.tensor(lowerCAmelCase__ ) __a = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts __a , __a = rename_base_flax_keys(tuple(key.split('''/''' ) ) , lowerCAmelCase__ ) __a = '''/'''.join(lowerCAmelCase__ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: __a = os.path.join( lowerCAmelCase__ , weights_name.replace('''.bin''' , f'''-{len(lowerCAmelCase__ )+1:05d}-of-???.bin''' ) ) rename_and_save_block(lowerCAmelCase__ , lowerCAmelCase__ ) sharded_state_dicts.append(current_block.keys() ) del current_block __a = {} __a = 0 __a = raw_weights.to(getattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) current_block_size += weight_size total_size += weight_size # Add the last block __a = os.path.join(lowerCAmelCase__ , weights_name.replace('''.bin''' , f'''-{len(lowerCAmelCase__ )+1:05d}-of-???.bin''' ) ) rename_and_save_block(lowerCAmelCase__ , lowerCAmelCase__ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(lowerCAmelCase__ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index __a = {} __a = {} for idx, shard in enumerate(lowerCAmelCase__ ): __a = weights_name.replace( '''.bin''' , f'''-{idx+1:05d}-of-{len(lowerCAmelCase__ ):05d}.bin''' ) # len(sharded_state_dicts):05d} __a = os.path.join(lowerCAmelCase__ , weights_name.replace('''.bin''' , f'''-{idx+1:05d}-of-???.bin''' ) ) os.rename(lowerCAmelCase__ , os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) ) __a = shard for key in shard: __a = shard_file # Add the metadata __a = {'''total_size''': total_size} __a = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) , '''w''' , encoding='''utf-8''' ) as f: __a = json.dumps(lowerCAmelCase__ , indent=2 , sort_keys=lowerCAmelCase__ ) + '''\n''' f.write(lowerCAmelCase__ ) return metadata, index if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) lowercase_ = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def lowercase ( ) -> int: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer __a = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' ) config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' ) __a = SwitchTransformersForConditionalGeneration.from_pretrained( '''/home/arthur_huggingface_co/transformers/switch_converted''' , device_map='''auto''' ) __a = TaTokenizer.from_pretrained('''t5-small''' ) __a = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' __a = tokenizer(lowerCAmelCase__ , return_tensors='''pt''' ).input_ids __a = model.generate(lowerCAmelCase__ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
65
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
65
1
"""simple docstring""" import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger lowercase_ = get_logger(__name__) lowercase_ = r"\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n search or log softmax for each vocabulary token when using beam search\n kwargs (`Dict[str, Any]`, *optional*):\n Additional logits processor specific kwargs.\n\n Return:\n `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n" class __lowerCAmelCase : '''simple docstring''' @add_start_docstrings(_a ) def __call__( self , _a , _a ): raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class __lowerCAmelCase : '''simple docstring''' @add_start_docstrings(_a ) def __call__( self , _a , _a ): raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @add_start_docstrings(_a ) def __call__( self , _a , _a , _a , **_a ): for processor in self: __a = inspect.signature(processor.__call__ ).parameters if len(_a ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( f'''Make sure that all the required parameters: {list(function_args.keys() )} for ''' f'''{processor.__class__} are passed to the logits processor.''' ) __a = processor(_a , _a , _a , **_a ) else: __a = processor(_a , _a , _a ) return scores class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a ): if not isinstance(_a , _a ) or not (temperature > 0): raise ValueError(f'''`temperature` has to be a strictly positive float, but is {temperature}''' ) __a = temperature def __call__( self , _a , _a , _a ): __a = scores / self.temperature return scores class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a = -float('''Inf''' ) , _a = 1 ): if not isinstance(_a , _a ) or (top_p < 0 or top_p > 1.0): raise ValueError(f'''`top_p` has to be a float > 0 and < 1, but is {top_p}''' ) if not isinstance(_a , _a ) or (min_tokens_to_keep < 1): raise ValueError(f'''`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}''' ) __a = top_p __a = filter_value __a = min_tokens_to_keep def __call__( self , _a , _a , _a ): __a , __a = lax.top_k(_a , scores.shape[-1] ) __a = jnp.full_like(_a , self.filter_value ) __a = jax.nn.softmax(_a , axis=-1 ).cumsum(axis=-1 ) __a = cumulative_probs < self.top_p # include the token that is higher than top_p as well __a = jnp.roll(_a , 1 ) score_mask |= score_mask.at[:, 0].set(_a ) # min tokens to keep __a = score_mask.at[:, : self.min_tokens_to_keep].set(_a ) __a = jnp.where(_a , _a , _a ) __a = jax.lax.sort_key_val(_a , _a )[-1] return next_scores class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a = -float('''Inf''' ) , _a = 1 ): if not isinstance(_a , _a ) or top_k <= 0: raise ValueError(f'''`top_k` has to be a strictly positive integer, but is {top_k}''' ) __a = max(_a , _a ) __a = filter_value def __call__( self , _a , _a , _a ): __a , __a = scores.shape __a = jnp.full(batch_size * vocab_size , self.filter_value ) __a = min(self.top_k , scores.shape[-1] ) # Safety check __a , __a = lax.top_k(_a , _a ) __a = jnp.broadcast_to((jnp.arange(_a ) * vocab_size)[:, None] , (batch_size, topk) ).flatten() __a = topk_scores.flatten() __a = topk_indices.flatten() + shift __a = next_scores_flat.at[topk_indices_flat].set(_a ) __a = next_scores_flat.reshape(_a , _a ) return next_scores class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a ): __a = bos_token_id def __call__( self , _a , _a , _a ): __a = jnp.full(scores.shape , -float('''inf''' ) ) __a = 1 - jnp.bool_(cur_len - 1 ) __a = jnp.where(_a , new_scores.at[:, self.bos_token_id].set(0 ) , _a ) return scores class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a ): __a = max_length __a = eos_token_id def __call__( self , _a , _a , _a ): __a = jnp.full(scores.shape , -float('''inf''' ) ) __a = 1 - jnp.bool_(cur_len - self.max_length + 1 ) __a = jnp.where(_a , new_scores.at[:, self.eos_token_id].set(0 ) , _a ) return scores class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a ): if not isinstance(_a , _a ) or min_length < 0: raise ValueError(f'''`min_length` has to be a positive integer, but is {min_length}''' ) if not isinstance(_a , _a ) or eos_token_id < 0: raise ValueError(f'''`eos_token_id` has to be a positive integer, but is {eos_token_id}''' ) __a = min_length __a = eos_token_id def __call__( self , _a , _a , _a ): # create boolean flag to decide if min length penalty should be applied __a = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 ) __a = jnp.where(_a , scores.at[:, self.eos_token_id].set(-float('''inf''' ) ) , _a ) return scores class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a ): __a = list(_a ) __a = begin_index def __call__( self , _a , _a , _a ): __a = 1 - jnp.bool_(cur_len - self.begin_index ) __a = jnp.where(_a , scores.at[:, self.begin_suppress_tokens].set(-float('''inf''' ) ) , _a ) return scores class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a ): __a = list(_a ) def __call__( self , _a , _a , _a ): __a = scores.at[..., self.suppress_tokens].set(-float('''inf''' ) ) return scores class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a ): __a = dict(_a ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. __a = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: __a = force_token_array.at[index].set(_a ) __a = jnp.intaa(_a ) def __call__( self , _a , _a , _a ): def _force_token(_a ): __a = scores.shape[0] __a = self.force_token_array[generation_idx] __a = jnp.ones_like(_a , dtype=scores.dtype ) * -float('''inf''' ) __a = jnp.zeros((batch_size, 1) , dtype=scores.dtype ) __a = lax.dynamic_update_slice(_a , _a , (0, current_token) ) return new_scores __a = lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(_a ) , lambda: scores , ) , ) return scores class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a ): __a = generate_config.eos_token_id __a = generate_config.no_timestamps_token_id __a = generate_config.no_timestamps_token_id + 1 __a = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(_a , '''max_initial_timestamp_index''' ): __a = generate_config.max_initial_timestamp_index else: __a = model_config.vocab_size if self.max_initial_timestamp_index is None: __a = model_config.vocab_size def __call__( self , _a , _a , _a ): # suppress <|notimestamps|> which is handled by without_timestamps __a = scores.at[:, self.no_timestamps_token_id].set(-float('''inf''' ) ) def handle_pairs(_a , _a ): __a = jnp.where((cur_len - self.begin_index) >= 1 , _a , _a ) __a = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , _a , ) __a = jnp.where((cur_len - self.begin_index) < 2 , _a , _a ) __a = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , _a , _a , ) return jnp.where( _a , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('''inf''' ) ) , scores_k.at[: self.eos_token_id].set(-float('''inf''' ) ) , ) , _a , ) __a = jax.vmap(_a )(_a , _a ) __a = jnp.where(cur_len == self.begin_index , _a , _a ) __a = jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , _a , ) __a = self.timestamp_begin + self.max_initial_timestamp_index __a = jnp.where( _a , scores.at[:, last_allowed + 1 :].set(-float('''inf''' ) ) , _a , ) # if sum of probability over timestamps is above any other token, sample timestamp __a = jax.nn.log_softmax(_a , axis=-1 ) def handle_cumulative_probs(_a , _a ): __a = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 ) __a = jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('''inf''' ) ) , _a , ) __a = jax.vmap(_a )(_a , _a ) return scores
65
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir("fixtures/test_sentencepiece_bpe_char.model") @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = SpeechTaTokenizer __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = True def __UpperCAmelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing __a = SpeechTaTokenizer(_a ) __a = AddedToken('''<mask>''' , lstrip=_a , rstrip=_a ) __a = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self , _a ): __a = '''this is a test''' __a = '''this is a test''' return input_text, output_text def __UpperCAmelCase ( self , _a , _a=False , _a=20 , _a=5 ): __a , __a = self.get_input_output_texts(_a ) __a = tokenizer.encode(_a , add_special_tokens=_a ) __a = tokenizer.decode(_a , clean_up_tokenization_spaces=_a ) return text, ids def __UpperCAmelCase ( self ): __a = '''<pad>''' __a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def __UpperCAmelCase ( self ): __a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(_a ) , 81 ) def __UpperCAmelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __UpperCAmelCase ( self ): __a = self.get_tokenizers(do_lower_case=_a ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) __a = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] __a = tokenizer.add_tokens(_a ) __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) self.assertEqual(_a , _a ) self.assertEqual(_a , len(_a ) ) self.assertEqual(_a , all_size + len(_a ) ) __a = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=_a ) self.assertGreaterEqual(len(_a ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) __a = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} __a = tokenizer.add_special_tokens(_a ) __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) self.assertEqual(_a , _a ) self.assertEqual(_a , len(_a ) ) self.assertEqual(_a , all_size_a + len(_a ) ) __a = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=_a ) self.assertGreaterEqual(len(_a ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = self.get_tokenizer() __a = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(_a , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) __a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) __a = tokenizer.convert_tokens_to_ids(_a ) # fmt: off self.assertListEqual(_a , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on __a = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def __UpperCAmelCase ( self ): # Use custom sequence because this tokenizer does not handle numbers. __a = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off __a = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=_a , )
65
1
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowercase_ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt") @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[str] = field( default='cifar10' , metadata={'help': 'Name of a dataset from the datasets package'} ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The column name of the images in the files.'} ) __UpperCAmelCase : Optional[str] = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'A folder containing the training data.'} ) __UpperCAmelCase : Optional[str] = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'A folder containing the validation data.'} ) __UpperCAmelCase : Optional[float] = field( default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} ) __UpperCAmelCase : Optional[int] = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) __UpperCAmelCase : Optional[int] = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def __UpperCAmelCase ( self ): __a = {} if self.train_dir is not None: __a = self.train_dir if self.validation_dir is not None: __a = self.validation_dir __a = data_files if data_files else None @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : str = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Pretrained config name or path if not the same as model_name_or_path'} ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'} ) __UpperCAmelCase : str = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) __UpperCAmelCase : str = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Name or path of preprocessor config.'} ) __UpperCAmelCase : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) __UpperCAmelCase : float = field( default=0.75 , metadata={'help': 'The ratio of the number of masked tokens in the input sequence.'} ) __UpperCAmelCase : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether or not to train with normalized pixel values as target.'} ) @dataclass class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : float = field( default=1e-3 , metadata={'help': 'Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'} ) def lowercase ( lowerCAmelCase__ : str ) -> List[str]: __a = torch.stack([example['''pixel_values'''] for example in examples] ) return {"pixel_values": pixel_values} def lowercase ( ) -> Any: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __a = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __a , __a , __a = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __a , __a , __a = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_mae''' , lowerCAmelCase__ , lowerCAmelCase__ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __a = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase__ ) transformers.utils.logging.set_verbosity(lowerCAmelCase__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(f'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. __a = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __a = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset. __a = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. __a = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , lowerCAmelCase__ ) and data_args.train_val_split > 0.0: __a = ds['''train'''].train_test_split(data_args.train_val_split ) __a = split['''train'''] __a = split['''test'''] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __a = { '''cache_dir''': model_args.cache_dir, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.config_name: __a = ViTMAEConfig.from_pretrained(model_args.config_name , **lowerCAmelCase__ ) elif model_args.model_name_or_path: __a = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase__ ) else: __a = ViTMAEConfig() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.config_overrides is not None: logger.info(f'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(f'''New config: {config}''' ) # adapt config config.update( { '''mask_ratio''': model_args.mask_ratio, '''norm_pix_loss''': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: __a = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **lowerCAmelCase__ ) elif model_args.model_name_or_path: __a = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase__ ) else: __a = ViTImageProcessor() # create model if model_args.model_name_or_path: __a = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=lowerCAmelCase__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('''Training new model from scratch''' ) __a = ViTMAEForPreTraining(lowerCAmelCase__ ) if training_args.do_train: __a = ds['''train'''].column_names else: __a = ds['''validation'''].column_names if data_args.image_column_name is not None: __a = data_args.image_column_name elif "image" in column_names: __a = '''image''' elif "img" in column_names: __a = '''img''' else: __a = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: __a = image_processor.size['''shortest_edge'''] else: __a = (image_processor.size['''height'''], image_processor.size['''width''']) __a = Compose( [ Lambda(lambda lowerCAmelCase__ : img.convert('''RGB''' ) if img.mode != "RGB" else img ), RandomResizedCrop(lowerCAmelCase__ , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(lowerCAmelCase__ : Any ): __a = [transforms(lowerCAmelCase__ ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: __a = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(lowerCAmelCase__ ) if training_args.do_eval: if "validation" not in ds: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: __a = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(lowerCAmelCase__ ) # Compute absolute learning rate __a = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: __a = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer __a = Trainer( model=lowerCAmelCase__ , args=lowerCAmelCase__ , train_dataset=ds['''train'''] if training_args.do_train else None , eval_dataset=ds['''validation'''] if training_args.do_eval else None , tokenizer=lowerCAmelCase__ , data_collator=lowerCAmelCase__ , ) # Training if training_args.do_train: __a = None if training_args.resume_from_checkpoint is not None: __a = training_args.resume_from_checkpoint elif last_checkpoint is not None: __a = last_checkpoint __a = trainer.train(resume_from_checkpoint=lowerCAmelCase__ ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: __a = trainer.evaluate() trainer.log_metrics('''eval''' , lowerCAmelCase__ ) trainer.save_metrics('''eval''' , lowerCAmelCase__ ) # Write model card and (optionally) push to hub __a = { '''tasks''': '''masked-auto-encoding''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-auto-encoding'''], } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase__ ) else: trainer.create_model_card(**lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Optional[Any] ) -> Optional[Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
65
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = ['input_features', 'attention_mask'] def __init__( self , _a=80 , _a=16_000 , _a=0.0 , _a=10 , _a=25 , _a="hamming_window" , _a=3_2768.0 , _a=0.97 , _a=1.0 , _a=True , _a=True , _a=False , **_a , ): super().__init__(feature_size=_a , sampling_rate=_a , padding_value=_a , **_a ) __a = feature_size __a = sampling_rate __a = padding_value __a = hop_length __a = win_length __a = frame_signal_scale __a = preemphasis_coeff __a = mel_floor __a = normalize_means __a = normalize_vars __a = win_function __a = return_attention_mask __a = win_length * sampling_rate // 1_000 __a = hop_length * sampling_rate // 1_000 __a = optimal_fft_length(self.sample_size ) __a = (self.n_fft // 2) + 1 def __UpperCAmelCase ( self , _a ): if self.win_function == "hamming_window": __a = window_function(window_length=self.sample_size , name=self.win_function , periodic=_a ) else: __a = window_function(window_length=self.sample_size , name=self.win_function ) __a = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) __a = spectrogram( one_waveform * self.frame_signal_scale , window=_a , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=_a , preemphasis=self.preemphasis_coeff , mel_filters=_a , mel_floor=self.mel_floor , log_mel='''log''' , ) return msfc_features.T def __UpperCAmelCase ( self , _a , _a , _a ): # make sure we normalize float32 arrays if self.normalize_means: __a = x[:input_length].mean(axis=0 ) __a = np.subtract(_a , _a ) if self.normalize_vars: __a = x[:input_length].std(axis=0 ) __a = np.divide(_a , _a ) if input_length < x.shape[0]: __a = padding_value # make sure array is in float32 __a = x.astype(np.floataa ) return x def __UpperCAmelCase ( self , _a , _a = None ): __a = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(_a , _a , self.padding_value ) for x, n in zip(_a , _a )] def __call__( self , _a , _a = False , _a = None , _a = False , _a = None , _a = None , _a = None , _a = None , **_a , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with''' f''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __a = isinstance(_a , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) __a = is_batched_numpy or ( isinstance(_a , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __a = [np.asarray(_a , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_a , np.ndarray ): __a = np.asarray(_a , dtype=np.floataa ) elif isinstance(_a , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __a = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __a = [raw_speech] # extract fbank features __a = [self._extract_mfsc_features(_a ) for one_waveform in raw_speech] # convert into correct format for padding __a = BatchFeature({'''input_features''': features} ) __a = self.pad( _a , padding=_a , max_length=_a , truncation=_a , pad_to_multiple_of=_a , return_attention_mask=_a , **_a , ) # make sure list is in array format __a = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , _a ): __a = [np.asarray(_a , dtype=np.floataa ) for feature in input_features] __a = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __a = [np.asarray(_a , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: __a = ( np.array(_a , dtype=np.intaa ) if self._get_padding_strategies(_a , max_length=_a ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) __a = self.normalize( padded_inputs['''input_features'''] , attention_mask=_a ) if return_tensors is not None: __a = padded_inputs.convert_to_tensors(_a ) return padded_inputs
65
1
"""simple docstring""" from collections.abc import Sequence def lowercase ( lowerCAmelCase__ : Sequence[float] , lowerCAmelCase__ : bool = False ) -> float: if not arr: return 0 __a = 0 if allow_empty_subarrays else float('''-inf''' ) __a = 0.0 for num in arr: __a = max(0 if allow_empty_subarrays else num , curr_sum + num ) __a = max(lowerCAmelCase__ , lowerCAmelCase__ ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() lowercase_ = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(F'''{max_subarray_sum(nums) = }''')
65
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env' ) @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue_model_parallelism.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_6_0_0, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_6_0_0, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, ] ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=_a , ) assert hasattr(self , '''env''' ) def __UpperCAmelCase ( self , _a ): # configuration for running training on smdistributed Model Parallel __a = { '''enabled''': True, '''processes_per_host''': 8, } __a = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __a = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __a = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=_a , instance_type=self.instance_type , debugger_hook_config=_a , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 500, } , metric_definitions=self.env.metric_definitions , distribution=_a , py_version='''py36''' , ) def __UpperCAmelCase ( self , _a ): TrainingJobAnalytics(_a ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __UpperCAmelCase ( self , _a ): # create estimator __a = self.create_estimator(_a ) # run training estimator.fit() # result dataframe __a = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __a = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 999_999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , _a )
65
1
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowercase_ = abspath(join(dirname(__file__), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[int]: config.addinivalue_line( '''markers''' , '''is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested''' ) config.addinivalue_line( '''markers''' , '''is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested''' ) config.addinivalue_line('''markers''' , '''is_pipeline_test: mark test to run only when pipelines are tested''' ) config.addinivalue_line('''markers''' , '''is_staging_test: mark test to run only in the staging environment''' ) config.addinivalue_line('''markers''' , '''accelerate_tests: mark test that require accelerate''' ) config.addinivalue_line('''markers''' , '''tool_tests: mark the tool tests that are run on their specific schedule''' ) def lowercase ( lowerCAmelCase__ : Union[str, Any] ) -> List[Any]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Union[str, Any] ) -> List[Any]: from transformers.testing_utils import pytest_terminal_summary_main __a = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(lowerCAmelCase__ , id=lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[str] ) -> Tuple: # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: __a = 0 # Doctest custom flag to ignore output. lowercase_ = doctest.register_optionflag("IGNORE_RESULT") lowercase_ = doctest.OutputChecker class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self , _a , _a , _a ): if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , _a , _a , _a ) lowercase_ = CustomOutputChecker lowercase_ = HfDoctestModule lowercase_ = HfDocTestParser
65
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
65
1
"""simple docstring""" from itertools import permutations def lowercase ( lowerCAmelCase__ : tuple ) -> bool: if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False __a = [7, 11, 13, 17] for i, test in enumerate(lowerCAmelCase__ ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def lowercase ( lowerCAmelCase__ : int = 10 ) -> int: return sum( int(''''''.join(map(lowerCAmelCase__ , lowerCAmelCase__ ) ) ) for num in permutations(range(lowerCAmelCase__ ) ) if is_substring_divisible(lowerCAmelCase__ ) ) if __name__ == "__main__": print(F'''{solution() = }''')
65
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable lowercase_ = {"configuration_gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["GPTNeoXTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXForCausalLM", "GPTNeoXForQuestionAnswering", "GPTNeoXForSequenceClassification", "GPTNeoXForTokenClassification", "GPTNeoXLayer", "GPTNeoXModel", "GPTNeoXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
65
1
"""simple docstring""" from collections import deque from .hash_table import HashTable class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , *_a , **_a ): super().__init__(*_a , **_a ) def __UpperCAmelCase ( self , _a , _a ): __a = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(_a ) __a = self.values[key] def __UpperCAmelCase ( self ): return ( sum(self.charge_factor - len(_a ) for slot in self.values ) / self.size_table * self.charge_factor ) def __UpperCAmelCase ( self , _a , _a=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(_a ) == 0 ): return key return super()._collision_resolution(_a , _a )
65
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=2 , _a=8 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=16 , _a=5 , _a=2 , _a=36 , _a="gelu" , _a=0.0 , _a=0.0 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self ): __a = self.get_config() __a = 300 return config def __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraModel(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a ) __a = model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = MraModel(_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , ) __a = model( _a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , ) __a = model(_a , attention_mask=_a , token_type_ids=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraForMaskedLM(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraForQuestionAnswering(config=_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , token_type_ids=_a , start_positions=_a , end_positions=_a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MraForSequenceClassification(_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MraForTokenClassification(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_choices __a = MraForMultipleChoice(config=_a ) model.to(_a ) model.eval() __a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) __UpperCAmelCase : str = False __UpperCAmelCase : Any = False __UpperCAmelCase : List[Any] = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Dict = () def __UpperCAmelCase ( self ): __a = MraModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a = type self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MraModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip(reason='''MRA does not output attentions''' ) def __UpperCAmelCase ( self ): return @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = MraModel.from_pretrained('''uw-madison/mra-base-512-4''' ) __a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4''' ) __a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = 50_265 __a = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3''' ) __a = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = 50_265 __a = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
65
1
"""simple docstring""" import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=4 , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_attention_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_choices def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_attention_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Tuple = True __UpperCAmelCase : Optional[Any] = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def __UpperCAmelCase ( self ): __a = FlaxRobertaModelTester(self ) @slow def __UpperCAmelCase ( self ): for model_class_name in self.all_model_classes: __a = model_class_name.from_pretrained('''roberta-base''' , from_pt=_a ) __a = model(np.ones((1, 1) ) ) self.assertIsNotNone(_a )
65
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> list[str]: if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number_of_bytes!''' ) __a = number_of_bytes // partitions __a = [] for i in range(lowerCAmelCase__ ): __a = i * bytes_per_partition + 1 __a = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
65
1
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __UpperCAmelCase : Dict = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def __UpperCAmelCase ( self , _a , _a , _a ): __a = TextaTextGenerationPipeline(model=_a , tokenizer=_a ) return generator, ["Something to write", "Something else"] def __UpperCAmelCase ( self , _a , _a ): __a = generator('''Something there''' ) self.assertEqual(_a , [{'''generated_text''': ANY(_a )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['''generated_text'''].startswith('''Something there''' ) ) __a = generator(['''This is great !''', '''Something else'''] , num_return_sequences=2 , do_sample=_a ) self.assertEqual( _a , [ [{'''generated_text''': ANY(_a )}, {'''generated_text''': ANY(_a )}], [{'''generated_text''': ANY(_a )}, {'''generated_text''': ANY(_a )}], ] , ) __a = generator( ['''This is great !''', '''Something else'''] , num_return_sequences=2 , batch_size=2 , do_sample=_a ) self.assertEqual( _a , [ [{'''generated_text''': ANY(_a )}, {'''generated_text''': ANY(_a )}], [{'''generated_text''': ANY(_a )}, {'''generated_text''': ANY(_a )}], ] , ) with self.assertRaises(_a ): generator(4 ) @require_torch def __UpperCAmelCase ( self ): __a = pipeline('''text2text-generation''' , model='''patrickvonplaten/t5-tiny-random''' , framework='''pt''' ) # do_sample=False necessary for reproducibility __a = generator('''Something there''' , do_sample=_a ) self.assertEqual(_a , [{'''generated_text''': ''''''}] ) __a = 3 __a = generator( '''Something there''' , num_return_sequences=_a , num_beams=_a , ) __a = [ {'''generated_text''': '''Beide Beide Beide Beide Beide Beide Beide Beide Beide'''}, {'''generated_text''': '''Beide Beide Beide Beide Beide Beide Beide Beide'''}, {'''generated_text''': ''''''}, ] self.assertEqual(_a , _a ) __a = generator('''This is a test''' , do_sample=_a , num_return_sequences=2 , return_tensors=_a ) self.assertEqual( _a , [ {'''generated_token_ids''': ANY(torch.Tensor )}, {'''generated_token_ids''': ANY(torch.Tensor )}, ] , ) __a = generator.model.config.eos_token_id __a = '''<pad>''' __a = generator( ['''This is a test''', '''This is a second test'''] , do_sample=_a , num_return_sequences=2 , batch_size=2 , return_tensors=_a , ) self.assertEqual( _a , [ [ {'''generated_token_ids''': ANY(torch.Tensor )}, {'''generated_token_ids''': ANY(torch.Tensor )}, ], [ {'''generated_token_ids''': ANY(torch.Tensor )}, {'''generated_token_ids''': ANY(torch.Tensor )}, ], ] , ) @require_tf def __UpperCAmelCase ( self ): __a = pipeline('''text2text-generation''' , model='''patrickvonplaten/t5-tiny-random''' , framework='''tf''' ) # do_sample=False necessary for reproducibility __a = generator('''Something there''' , do_sample=_a ) self.assertEqual(_a , [{'''generated_text''': ''''''}] )
65
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> list: __a = len(lowerCAmelCase__ ) __a = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): __a = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
65
1
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = field(default='image-classification' , metadata={'include_in_asdict_even_if_is_default': True} ) __UpperCAmelCase : ClassVar[Features] = Features({'image': Image()} ) __UpperCAmelCase : ClassVar[Features] = Features({'labels': ClassLabel} ) __UpperCAmelCase : str = "image" __UpperCAmelCase : str = "labels" def __UpperCAmelCase ( self , _a ): if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , _a ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __a = copy.deepcopy(self ) __a = self.label_schema.copy() __a = features[self.label_column] __a = label_schema return task_template @property def __UpperCAmelCase ( self ): return { self.image_column: "image", self.label_column: "labels", }
65
"""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 lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} lowercase_ = { "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" ), }, } lowercase_ = { "allenai/longformer-base-4096": 4_0_9_6, "allenai/longformer-large-4096": 4_0_9_6, "allenai/longformer-large-4096-finetuned-triviaqa": 4_0_9_6, "allenai/longformer-base-4096-extra.pos.embd.only": 4_0_9_6, "allenai/longformer-large-4096-extra.pos.embd.only": 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowercase ( ) -> Union[str, Any]: __a = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __a = bs[:] __a = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCAmelCase__ ) cs.append(2**8 + n ) n += 1 __a = [chr(lowerCAmelCase__ ) for n in cs] return dict(zip(lowerCAmelCase__ , lowerCAmelCase__ ) ) def lowercase ( lowerCAmelCase__ : Tuple ) -> Tuple: __a = set() __a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __a = char return pairs class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = VOCAB_FILES_NAMES __UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Union[str, Any] = ['input_ids', 'attention_mask'] def __init__( self , _a , _a , _a="replace" , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=False , **_a , ): __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else bos_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else sep_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else cls_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( errors=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , **_a , ) with open(_a , encoding='''utf-8''' ) as vocab_handle: __a = json.load(_a ) __a = {v: k for k, v in self.encoder.items()} __a = errors # how to handle errors in decoding __a = bytes_to_unicode() __a = {v: k for k, v in self.byte_encoder.items()} with open(_a , encoding='''utf-8''' ) as merges_handle: __a = merges_handle.read().split('''\n''' )[1:-1] __a = [tuple(merge.split() ) for merge in bpe_merges] __a = dict(zip(_a , range(len(_a ) ) ) ) __a = {} __a = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __a = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def __UpperCAmelCase ( self ): return len(self.encoder ) def __UpperCAmelCase ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def __UpperCAmelCase ( self , _a ): if token in self.cache: return self.cache[token] __a = tuple(_a ) __a = get_pairs(_a ) if not pairs: return token while True: __a = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __a , __a = bigram __a = [] __a = 0 while i < len(_a ): try: __a = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __a = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __a = tuple(_a ) __a = new_word if len(_a ) == 1: break else: __a = get_pairs(_a ) __a = ''' '''.join(_a ) __a = word return word def __UpperCAmelCase ( self , _a ): __a = [] for token in re.findall(self.pat , _a ): __a = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(''' ''' ) ) return bpe_tokens def __UpperCAmelCase ( self , _a ): return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def __UpperCAmelCase ( self , _a ): return self.decoder.get(_a ) def __UpperCAmelCase ( self , _a ): __a = ''''''.join(_a ) __a = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def __UpperCAmelCase ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_a , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '''\n''' ) __a = 0 with open(_a , '''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 _a : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __a = token_index writer.write(''' '''.join(_a ) + '''\n''' ) index += 1 return vocab_file, merge_file def __UpperCAmelCase ( self , _a , _a = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __a = [self.cls_token_id] __a = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __UpperCAmelCase ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self , _a , _a=False , **_a ): __a = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): __a = ''' ''' + text return (text, kwargs)
65
1
"""simple docstring""" import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Union[str, Any]=None ) -> str: __a = None if token is not None: __a = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f'''Bearer {token}'''} __a = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' __a = requests.get(lowerCAmelCase__ , headers=lowerCAmelCase__ ).json() __a = {} try: job_links.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) __a = math.ceil((result['''total_count'''] - 100) / 100 ) for i in range(lowerCAmelCase__ ): __a = requests.get(url + f'''&page={i + 2}''' , headers=lowerCAmelCase__ ).json() job_links.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : int=None ) -> Any: __a = None if token is not None: __a = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f'''Bearer {token}'''} __a = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' __a = requests.get(lowerCAmelCase__ , headers=lowerCAmelCase__ ).json() __a = {} try: artifacts.update({artifact['''name''']: artifact['''archive_download_url'''] for artifact in result['''artifacts''']} ) __a = math.ceil((result['''total_count'''] - 100) / 100 ) for i in range(lowerCAmelCase__ ): __a = requests.get(url + f'''&page={i + 2}''' , headers=lowerCAmelCase__ ).json() artifacts.update({artifact['''name''']: artifact['''archive_download_url'''] for artifact in result['''artifacts''']} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[Any] ) -> Dict: __a = None if token is not None: __a = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f'''Bearer {token}'''} __a = requests.get(lowerCAmelCase__ , headers=lowerCAmelCase__ , allow_redirects=lowerCAmelCase__ ) __a = result.headers['''Location'''] __a = requests.get(lowerCAmelCase__ , allow_redirects=lowerCAmelCase__ ) __a = os.path.join(lowerCAmelCase__ , f'''{artifact_name}.zip''' ) with open(lowerCAmelCase__ , '''wb''' ) as fp: fp.write(response.content ) def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str]=None ) -> List[Any]: __a = [] __a = [] __a = None with zipfile.ZipFile(lowerCAmelCase__ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(lowerCAmelCase__ ) as f: for line in f: __a = line.decode('''UTF-8''' ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs __a = line[: line.index(''': ''' )] __a = line[line.index(''': ''' ) + len(''': ''' ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith('''FAILED ''' ): # `test` is the test method that failed __a = line[len('''FAILED ''' ) :] failed_tests.append(lowerCAmelCase__ ) elif filename == "job_name.txt": __a = line if len(lowerCAmelCase__ ) != len(lowerCAmelCase__ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(lowerCAmelCase__ )} for `errors` ''' f'''and {len(lowerCAmelCase__ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' ''' problem.''' ) __a = None if job_name and job_links: __a = job_links.get(lowerCAmelCase__ , lowerCAmelCase__ ) # A list with elements of the form (line of error, error, failed test) __a = [x + [y] + [job_link] for x, y in zip(lowerCAmelCase__ , lowerCAmelCase__ )] return result def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Any=None ) -> Dict: __a = [] __a = [os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) for p in os.listdir(lowerCAmelCase__ ) if p.endswith('''.zip''' )] for p in paths: errors.extend(get_errors_from_single_artifact(lowerCAmelCase__ , job_links=lowerCAmelCase__ ) ) return errors def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Union[str, Any]=None ) -> Optional[Any]: __a = Counter() counter.update([x[1] for x in logs] ) __a = counter.most_common() __a = {} for error, count in counts: if error_filter is None or error not in error_filter: __a = {'''count''': count, '''failed_tests''': [(x[2], x[0]) for x in logs if x[1] == error]} __a = dict(sorted(r.items() , key=lambda lowerCAmelCase__ : item[1]["count"] , reverse=lowerCAmelCase__ ) ) return r def lowercase ( lowerCAmelCase__ : Optional[Any] ) -> str: __a = test.split('''::''' )[0] if test.startswith('''tests/models/''' ): __a = test.split('''/''' )[2] else: __a = None return test def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any]=None ) -> int: __a = [(x[0], x[1], get_model(x[2] )) for x in logs] __a = [x for x in logs if x[2] is not None] __a = {x[2] for x in logs} __a = {} for test in tests: __a = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) __a = counter.most_common() __a = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} __a = sum(error_counts.values() ) if n_errors > 0: __a = {'''count''': n_errors, '''errors''': error_counts} __a = dict(sorted(r.items() , key=lambda lowerCAmelCase__ : item[1]["count"] , reverse=lowerCAmelCase__ ) ) return r def lowercase ( lowerCAmelCase__ : Optional[Any] ) -> Dict: __a = '''| no. | error | status |''' __a = '''|-:|:-|:-|''' __a = [header, sep] for error in reduced_by_error: __a = reduced_by_error[error]['''count'''] __a = f'''| {count} | {error[:100]} | |''' lines.append(lowerCAmelCase__ ) return "\n".join(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Tuple ) -> Any: __a = '''| model | no. of errors | major error | count |''' __a = '''|-:|-:|-:|-:|''' __a = [header, sep] for model in reduced_by_model: __a = reduced_by_model[model]['''count'''] __a , __a = list(reduced_by_model[model]['''errors'''].items() )[0] __a = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(lowerCAmelCase__ ) return "\n".join(lowerCAmelCase__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") parser.add_argument( "--output_dir", type=str, required=True, help="Where to store the downloaded artifacts and other result files.", ) parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") lowercase_ = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) lowercase_ = get_job_links(args.workflow_run_id, token=args.token) lowercase_ = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: lowercase_ = k.find(" / ") lowercase_ = k[index + len(" / ") :] lowercase_ = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) lowercase_ = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) lowercase_ = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error lowercase_ = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors lowercase_ = counter.most_common(3_0) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) lowercase_ = reduce_by_error(errors) lowercase_ = reduce_by_model(errors) lowercase_ = make_github_table(reduced_by_error) lowercase_ = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
65
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "unc-nlp/lxmert-base-uncased": "https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = 'lxmert' __UpperCAmelCase : str = {} def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=9_500 , _a=1_600 , _a=400 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=9 , _a=5 , _a=5 , _a=2_048 , _a=4 , _a=6.67 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=True , _a=True , **_a , ): __a = vocab_size __a = hidden_size __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = num_qa_labels __a = num_object_labels __a = num_attr_labels __a = l_layers __a = x_layers __a = r_layers __a = visual_feat_dim __a = visual_pos_dim __a = visual_loss_normalizer __a = task_matched __a = task_mask_lm __a = task_obj_predict __a = task_qa __a = visual_obj_loss __a = visual_attr_loss __a = visual_feat_loss __a = {'''vision''': r_layers, '''cross_encoder''': x_layers, '''language''': l_layers} super().__init__(**_a )
65
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "SCUT-DLVCLab/lilt-roberta-en-base": ( "https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json" ), } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = 'lilt' def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=0 , _a="absolute" , _a=None , _a=4 , _a=1_024 , **_a , ): super().__init__(pad_token_id=_a , **_a ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = position_embedding_type __a = classifier_dropout __a = channel_shrink_ratio __a = max_ad_position_embeddings
65
"""simple docstring""" import itertools import math def lowercase ( lowerCAmelCase__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( ) -> int: __a = 2 while True: if is_prime(lowerCAmelCase__ ): yield num num += 1 def lowercase ( lowerCAmelCase__ : int = 10001 ) -> int: return next(itertools.islice(prime_generator() , nth - 1 , lowerCAmelCase__ ) ) if __name__ == "__main__": print(F'''{solution() = }''')
65
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , *_a , **_a ): warnings.warn( '''The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use BeitImageProcessor instead.''' , _a , ) super().__init__(*_a , **_a )
65
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase_ = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
65
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase_ = { "configuration_bridgetower": [ "BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP", "BridgeTowerConfig", "BridgeTowerTextConfig", "BridgeTowerVisionConfig", ], "processing_bridgetower": ["BridgeTowerProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["BridgeTowerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST", "BridgeTowerForContrastiveLearning", "BridgeTowerForImageAndTextRetrieval", "BridgeTowerForMaskedLM", "BridgeTowerModel", "BridgeTowerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
65
"""simple docstring""" from sklearn.metrics import fa_score import datasets lowercase_ = "\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n" lowercase_ = "\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {'f1': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results['f1'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results['f1'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n >>> print(round(results['f1'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'f1': array([0.8, 0. , 0. ])}\n" lowercase_ = "\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def __UpperCAmelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'''] , ) def __UpperCAmelCase ( self , _a , _a , _a=None , _a=1 , _a="binary" , _a=None ): __a = fa_score( _a , _a , labels=_a , pos_label=_a , average=_a , sample_weight=_a ) return {"f1": float(_a ) if score.size == 1 else score}
65
1
"""simple docstring""" from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING lowercase_ = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , *_a , **_a ): super().__init__(*_a , **_a ) requires_backends(self , '''vision''' ) self.check_model_type(_a ) def __call__( self , _a , **_a ): return super().__call__(_a , **_a ) def __UpperCAmelCase ( self , **_a ): return {}, {}, {} def __UpperCAmelCase ( self , _a ): __a = load_image(_a ) __a = image.size __a = self.image_processor(images=_a , return_tensors=self.framework ) return model_inputs def __UpperCAmelCase ( self , _a ): __a = self.model(**_a ) return model_outputs def __UpperCAmelCase ( self , _a ): __a = model_outputs.predicted_depth __a = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='''bicubic''' , align_corners=_a ) __a = prediction.squeeze().cpu().numpy() __a = (output * 255 / np.max(_a )).astype('''uint8''' ) __a = Image.fromarray(_a ) __a = {} __a = predicted_depth __a = depth return output_dict
65
"""simple docstring""" from ..utils import DummyObject, requires_backends class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = ['onnx'] def __init__( self , *_a , **_a ): requires_backends(self , ['''onnx'''] ) @classmethod def __UpperCAmelCase ( cls , *_a , **_a ): requires_backends(cls , ['''onnx'''] ) @classmethod def __UpperCAmelCase ( cls , *_a , **_a ): requires_backends(cls , ['''onnx'''] )
65
1
"""simple docstring""" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' pass class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' pass class __lowerCAmelCase : '''simple docstring''' def __init__( self ): __a = [ [], [], [], ] def __UpperCAmelCase ( self , _a , _a ): try: if len(self.queues[priority] ) >= 100: raise OverflowError('''Maximum queue size is 100''' ) self.queues[priority].append(_a ) except IndexError: raise ValueError('''Valid priorities are 0, 1, and 2''' ) def __UpperCAmelCase ( self ): for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('''All queues are empty''' ) def __str__( self ): return "\n".join(f'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class __lowerCAmelCase : '''simple docstring''' def __init__( self ): __a = [] def __UpperCAmelCase ( self , _a ): if len(self.queue ) == 100: raise OverFlowError('''Maximum queue size is 100''' ) self.queue.append(_a ) def __UpperCAmelCase ( self ): if not self.queue: raise UnderFlowError('''The queue is empty''' ) else: __a = min(self.queue ) self.queue.remove(_a ) return data def __str__( self ): return str(self.queue ) def lowercase ( ) -> Tuple: __a = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 100 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 128 ) print(lowerCAmelCase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowerCAmelCase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def lowercase ( ) -> List[str]: __a = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(100 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(128 ) print(lowerCAmelCase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowerCAmelCase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
65
"""simple docstring""" import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin lowercase_ = 1e-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=16 , _a=13 , _a=7 , _a=14 , _a=10 , _a=19 , _a=5 , _a=4 , _a=True , _a=16 , _a=2 , _a=4 , _a=4 , _a="gelu" , _a=0.1 , _a=0.1 , _a=[1, 2, 3, 4, 5] , _a=25 , _a=5 , ): __a = d_model __a = parent __a = batch_size __a = prediction_length __a = context_length __a = cardinality __a = num_time_features __a = lags_sequence __a = embedding_dimension __a = is_training __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = context_length __a = prediction_length + label_length __a = label_length __a = moving_average __a = autocorrelation_factor def __UpperCAmelCase ( self ): return AutoformerConfig( d_model=self.d_model , 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 , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def __UpperCAmelCase ( self , _a ): __a = config.context_length + max(config.lags_sequence ) __a = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) __a = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) __a = floats_tensor([self.batch_size, _past_length] ) __a = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs __a = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) __a = floats_tensor([self.batch_size, config.prediction_length] ) __a = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def __UpperCAmelCase ( self ): __a = self.get_config() __a = self.prepare_autoformer_inputs_dict(_a ) return config, inputs_dict def __UpperCAmelCase ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def __UpperCAmelCase ( self , _a , _a ): __a = AutoformerModel(config=_a ).to(_a ).eval() __a = model(**_a ) __a = outputs.encoder_last_hidden_state __a = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: __a = model.get_encoder() encoder.save_pretrained(_a ) __a = AutoformerEncoder.from_pretrained(_a ).to(_a ) __a , __a , __a , __a , __a = model.create_network_inputs(**_a ) __a , __a = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) __a = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) __a = encoder(inputs_embeds=_a )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) __a = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) __a = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) __a = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) __a = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: __a = model.get_decoder() decoder.save_pretrained(_a ) __a = AutoformerDecoder.from_pretrained(_a ).to(_a ) __a = decoder( trend=_a , inputs_embeds=_a , encoder_hidden_states=_a , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Any = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () __UpperCAmelCase : int = (AutoformerForPrediction,) if is_torch_available() else () __UpperCAmelCase : Any = {'feature-extraction': AutoformerModel} if is_torch_available() else {} __UpperCAmelCase : int = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : int = False __UpperCAmelCase : Any = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : int = False def __UpperCAmelCase ( self ): __a = AutoformerModelTester(self ) __a = ConfigTester(self , config_class=_a , has_text_modality=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: __a = model_class(_a ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_a ) __a , __a = model_class.from_pretrained(_a , output_loading_info=_a ) self.assertEqual(info['''missing_keys'''] , [] ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*_a ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = inspect.signature(getattr(_a , '''forward''' ) ) # The main input is the name of the argument after `self` __a = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''' ) expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ] ) self.assertListEqual(arg_names[: len(_a )] , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True __a = getattr(self.model_tester , '''seq_length''' , _a ) __a = getattr(self.model_tester , '''decoder_seq_length''' , _a ) __a = getattr(self.model_tester , '''encoder_seq_length''' , _a ) __a = getattr(self.model_tester , '''d_model''' , _a ) __a = getattr(self.model_tester , '''num_attention_heads''' , _a ) __a = d_model // num_attention_heads for model_class in self.all_model_classes: __a = True __a = False __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.encoder_attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) __a = len(_a ) __a = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(_a , _a ) # decoder attentions __a = outputs.decoder_attentions self.assertIsInstance(_a , (list, tuple) ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions __a = outputs.cross_attentions self.assertIsInstance(_a , (list, tuple) ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine __a = True __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + 2 , len(_a ) ) __a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def __UpperCAmelCase ( self ): super().test_retain_grad_hidden_states_attentions() def lowercase ( lowerCAmelCase__ : Optional[int]="train-batch.pt" ) -> List[str]: __a = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=lowerCAmelCase__ , repo_type='''dataset''' ) __a = torch.load(lowerCAmelCase__ , map_location=lowerCAmelCase__ ) return batch @require_torch @slow class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch() with torch.no_grad(): __a = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] __a = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=_a ) self.assertTrue(torch.allclose(output[0, :3, :3] , _a , atol=_a ) ) def __UpperCAmelCase ( self ): __a = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): __a = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state __a = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=_a ) self.assertTrue(torch.allclose(output[0, :3, :3] , _a , atol=_a ) ) def __UpperCAmelCase ( self ): __a = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): __a = model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) __a = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , _a ) __a = torch.tensor([3130.6763, 4056.5293, 7053.0786] , device=_a ) __a = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , _a , rtol=1E-1 ) )
65
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase_ = { "configuration_mobilevit": ["MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileViTConfig", "MobileViTOnnxConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["MobileViTFeatureExtractor"] lowercase_ = ["MobileViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileViTForImageClassification", "MobileViTForSemanticSegmentation", "MobileViTModel", "MobileViTPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFMobileViTForImageClassification", "TFMobileViTForSemanticSegmentation", "TFMobileViTModel", "TFMobileViTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
65
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str] ) -> Any: if isinstance(lowerCAmelCase__ , torch.Tensor ): return image elif isinstance(lowerCAmelCase__ , PIL.Image.Image ): __a = [image] if isinstance(image[0] , PIL.Image.Image ): __a = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] __a = np.concatenate(lowerCAmelCase__ , axis=0 ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 2_55.0 __a = image.transpose(0 , 3 , 1 , 2 ) __a = 2.0 * image - 1.0 __a = torch.from_numpy(lowerCAmelCase__ ) elif isinstance(image[0] , torch.Tensor ): __a = torch.cat(lowerCAmelCase__ , dim=0 ) return image def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[int]=0.99_95 ) -> int: if not isinstance(lowerCAmelCase__ , np.ndarray ): __a = True __a = va.device __a = va.cpu().numpy() __a = va.cpu().numpy() __a = np.sum(va * va / (np.linalg.norm(lowerCAmelCase__ ) * np.linalg.norm(lowerCAmelCase__ )) ) if np.abs(lowerCAmelCase__ ) > DOT_THRESHOLD: __a = (1 - t) * va + t * va else: __a = np.arccos(lowerCAmelCase__ ) __a = np.sin(lowerCAmelCase__ ) __a = theta_a * t __a = np.sin(lowerCAmelCase__ ) __a = np.sin(theta_a - theta_t ) / sin_theta_a __a = sin_theta_t / sin_theta_a __a = sa * va + sa * va if inputs_are_torch: __a = torch.from_numpy(lowerCAmelCase__ ).to(lowerCAmelCase__ ) return va def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[Any] ) -> int: __a = F.normalize(lowerCAmelCase__ , dim=-1 ) __a = F.normalize(lowerCAmelCase__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ) -> List[str]: for param in model.parameters(): __a = value class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a=None , _a=None , _a=None , ): super().__init__() self.register_modules( vae=_a , text_encoder=_a , clip_model=_a , tokenizer=_a , unet=_a , scheduler=_a , feature_extractor=_a , coca_model=_a , coca_tokenizer=_a , coca_transform=_a , ) __a = ( feature_extractor.size if isinstance(feature_extractor.size , _a ) else feature_extractor.size['''shortest_edge'''] ) __a = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , _a ) set_requires_grad(self.clip_model , _a ) def __UpperCAmelCase ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def __UpperCAmelCase ( self ): self.enable_attention_slicing(_a ) def __UpperCAmelCase ( self ): set_requires_grad(self.vae , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.vae , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.unet , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.unet , _a ) def __UpperCAmelCase ( self , _a , _a , _a ): # get the original timestep using init_timestep __a = min(int(num_inference_steps * strength ) , _a ) __a = max(num_inference_steps - init_timestep , 0 ) __a = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a=None ): if not isinstance(_a , torch.Tensor ): raise ValueError(f'''`image` has to be of type `torch.Tensor` but is {type(_a )}''' ) __a = image.to(device=_a , dtype=_a ) if isinstance(_a , _a ): __a = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_a ) ] __a = torch.cat(_a , dim=0 ) else: __a = self.vae.encode(_a ).latent_dist.sample(_a ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 0.1_8215 * init_latents __a = init_latents.repeat_interleave(_a , dim=0 ) __a = randn_tensor(init_latents.shape , generator=_a , device=_a , dtype=_a ) # get latents __a = self.scheduler.add_noise(_a , _a , _a ) __a = init_latents return latents def __UpperCAmelCase ( self , _a ): __a = self.coca_transform(_a ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): __a = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) __a = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def __UpperCAmelCase ( self , _a , _a ): __a = self.feature_extractor.preprocess(_a ) __a = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() __a = self.clip_model.get_image_features(_a ) __a = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_a ) __a = image_embeddings_clip.repeat_interleave(_a , dim=0 ) return image_embeddings_clip @torch.enable_grad() def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): __a = latents.detach().requires_grad_() __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a , encoder_hidden_states=_a ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): __a = self.scheduler.alphas_cumprod[timestep] __a = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __a = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 __a = torch.sqrt(_a ) __a = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , _a ): __a = self.scheduler.sigmas[index] __a = latents - sigma * noise_pred else: raise ValueError(f'''scheduler type {type(self.scheduler )} not supported''' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 1 / 0.1_8215 * sample __a = self.vae.decode(_a ).sample __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = transforms.Resize(self.feature_extractor_size )(_a ) __a = self.normalize(_a ).to(latents.dtype ) __a = self.clip_model.get_image_features(_a ) __a = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_a ) __a = spherical_dist_loss(_a , _a ).mean() * clip_guidance_scale __a = -torch.autograd.grad(_a , _a )[0] if isinstance(self.scheduler , _a ): __a = latents.detach() + grads * (sigma**2) __a = noise_pred_original else: __a = noise_pred_original - torch.sqrt(_a ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , _a , _a , _a = None , _a = None , _a = 512 , _a = 512 , _a = 0.6 , _a = 50 , _a = 7.5 , _a = 1 , _a = 0.0 , _a = 100 , _a = None , _a = "pil" , _a = True , _a = 0.8 , _a = 0.1 , _a = 0.1 , ): if isinstance(_a , _a ) and len(_a ) != batch_size: raise ValueError(f'''You have passed {batch_size} batch_size, but only {len(_a )} generators.''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if isinstance(_a , torch.Generator ) and batch_size > 1: __a = [generator] + [None] * (batch_size - 1) __a = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] __a = [x[0] for x in coca_is_none if x[1]] __a = ''', '''.join(_a ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(_a ): raise ValueError( f'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' f'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) __a = self.get_image_description(_a ) if style_prompt is None: if len(_a ): raise ValueError( f'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' f''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) __a = self.get_image_description(_a ) # get prompt text embeddings for content and style __a = self.tokenizer( _a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=_a , return_tensors='''pt''' , ) __a = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] __a = self.tokenizer( _a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=_a , return_tensors='''pt''' , ) __a = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] __a = slerp(_a , _a , _a ) # duplicate text embeddings for each generation per prompt __a = text_embeddings.repeat_interleave(_a , dim=0 ) # set timesteps __a = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) __a = {} if accepts_offset: __a = 1 self.scheduler.set_timesteps(_a , **_a ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) __a , __a = self.get_timesteps(_a , _a , self.device ) __a = timesteps[:1].repeat(_a ) # Preprocess image __a = preprocess(_a , _a , _a ) __a = self.prepare_latents( _a , _a , _a , text_embeddings.dtype , self.device , _a ) __a = preprocess(_a , _a , _a ) __a = self.prepare_latents( _a , _a , _a , text_embeddings.dtype , self.device , _a ) __a = slerp(_a , _a , _a ) if clip_guidance_scale > 0: __a = self.get_clip_image_embeddings(_a , _a ) __a = self.get_clip_image_embeddings(_a , _a ) __a = slerp( _a , _a , _a ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __a = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __a = content_text_input.input_ids.shape[-1] __a = self.tokenizer([''''''] , padding='''max_length''' , max_length=_a , return_tensors='''pt''' ) __a = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt __a = uncond_embeddings.repeat_interleave(_a , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __a = 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`. __a = (batch_size, self.unet.config.in_channels, height // 8, width // 8) __a = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps __a = torch.randn(_a , generator=_a , device='''cpu''' , dtype=_a ).to( self.device ) else: __a = torch.randn(_a , generator=_a , device=self.device , dtype=_a ) else: if latents.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) __a = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __a = 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] __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta # check if the scheduler accepts generator __a = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: __a = generator with self.progress_bar(total=_a ): for i, t in enumerate(_a ): # expand the latents if we are doing classifier free guidance __a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a , encoder_hidden_states=_a ).sample # perform classifier free guidance if do_classifier_free_guidance: __a , __a = noise_pred.chunk(2 ) __a = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: __a = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) __a , __a = self.cond_fn( _a , _a , _a , _a , _a , _a , _a , ) # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 1 / 0.1_8215 * latents __a = self.vae.decode(_a ).sample __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=_a , nsfw_content_detected=_a )
65
1
"""simple docstring""" import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers lowercase_ = "python tqdm regex requests packaging filelock numpy tokenizers".split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append("dataclasses") if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append("importlib_metadata") for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(F'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''') def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any]=None ) -> Tuple: require_version(deps[pkg] , lowerCAmelCase__ )
65
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowercase_ = abspath(join(dirname(dirname(dirname(__file__))), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def lowercase ( lowerCAmelCase__ : List[Any] ) -> str: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int ) -> Union[str, Any]: from transformers.testing_utils import pytest_terminal_summary_main __a = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(lowerCAmelCase__ , id=lowerCAmelCase__ )
65
1
"""simple docstring""" import copy import os import cva import numpy as np from matplotlib import pyplot as plt class __lowerCAmelCase : '''simple docstring''' def __init__( self ): __a = '''''' __a = '''''' __a = [] __a = 0 __a = 256 __a = 0 __a = 0 __a = 0 __a = 0 def __UpperCAmelCase ( self , _a ): __a = cva.imread(_a , 0 ) __a = copy.deepcopy(self.img ) __a , __a , __a = plt.hist(self.img.ravel() , 256 , [0, 256] , label='''x''' ) __a = np.sum(_a ) for i in range(len(_a ) ): __a = x[i] / self.k self.sk += prk __a = (self.L - 1) * self.sk if self.rem != 0: __a = int(last % last ) __a = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(_a ) __a = int(np.ma.count(self.img ) / self.img[1].size ) __a = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): __a = self.img[j][i] if num != self.last_list[num]: __a = self.last_list[num] cva.imwrite('''output_data/output.jpg''' , self.img ) def __UpperCAmelCase ( self ): plt.hist(self.img.ravel() , 256 , [0, 256] ) def __UpperCAmelCase ( self ): cva.imshow('''Output-Image''' , self.img ) cva.imshow('''Input-Image''' , self.original_image ) cva.waitKey(5_000 ) cva.destroyAllWindows() if __name__ == "__main__": lowercase_ = os.path.join(os.path.basename(__file__), "image_data/input.jpg") lowercase_ = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
65
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase_ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __UpperCAmelCase : Any = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __UpperCAmelCase : Any = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __UpperCAmelCase : Dict = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def __UpperCAmelCase ( self , _a , _a , _a ): __a = ZeroShotClassificationPipeline( model=_a , tokenizer=_a , candidate_labels=['''polics''', '''health'''] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def __UpperCAmelCase ( self , _a , _a ): __a = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics''' ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) # No kwarg __a = classifier('''Who are you voting for in 2020?''' , ['''politics'''] ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics'''] ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics, public health''' ) self.assertEqual( _a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health'''] ) self.assertEqual( _a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) __a = classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''This text is about {}''' ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) # https://github.com/huggingface/transformers/issues/13846 __a = classifier(['''I am happy'''] , ['''positive''', '''negative'''] ) self.assertEqual( _a , [ {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} for i in range(1 ) ] , ) __a = classifier(['''I am happy''', '''I am sad'''] , ['''positive''', '''negative'''] ) self.assertEqual( _a , [ {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} for i in range(2 ) ] , ) with self.assertRaises(_a ): classifier('''''' , candidate_labels='''politics''' ) with self.assertRaises(_a ): classifier(_a , candidate_labels='''politics''' ) with self.assertRaises(_a ): classifier('''Who are you voting for in 2020?''' , candidate_labels='''''' ) with self.assertRaises(_a ): classifier('''Who are you voting for in 2020?''' , candidate_labels=_a ) with self.assertRaises(_a ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''Not formatting template''' , ) with self.assertRaises(_a ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template=_a , ) self.run_entailment_id(_a ) def __UpperCAmelCase ( self , _a ): __a = zero_shot_classifier.model.config __a = config.labelaid __a = zero_shot_classifier.entailment_id __a = {'''LABEL_0''': 0, '''LABEL_1''': 1, '''LABEL_2''': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) __a = {'''entailment''': 0, '''neutral''': 1, '''contradiction''': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __a = {'''ENTAIL''': 0, '''NON-ENTAIL''': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __a = {'''ENTAIL''': 2, '''NEUTRAL''': 1, '''CONTR''': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) __a = original_labelaid self.assertEqual(_a , zero_shot_classifier.entailment_id ) @require_torch def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( '''Who are you voting for in 2020?''' * 100 , candidate_labels=['''politics''', '''public health''', '''science'''] ) @require_torch def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @require_tf def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''tf''' , ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @slow @require_torch def __UpperCAmelCase ( self ): __a = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''pt''' ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) __a = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=_a , ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , ) @slow @require_tf def __UpperCAmelCase ( self ): __a = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''tf''' ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) __a = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=_a , ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , )
65
1
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : List[str] = 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 > 3317044064679887385961981 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 __a = [ 2047, 1373653, 25326001, 3215031751, 2152302898747, 3474749660383, 341550071728321, 1, 3825123056546413051, 1, 1, 318665857834031151167461, 3317044064679887385961981, ] __a = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(SCREAMING_SNAKE_CASE_ , 1 ): if n < _p: # then we have our last prime to check __a = primes[:idx] break __a , __a = 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: __a = False for r in range(SCREAMING_SNAKE_CASE_ ): __a = pow(SCREAMING_SNAKE_CASE_ , d * 2**r , SCREAMING_SNAKE_CASE_ ) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): __a = 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 lowercase ( ) -> None: assert not miller_rabin(561 ) assert miller_rabin(563 ) # 2047 assert not miller_rabin(838201 ) assert miller_rabin(838207 ) # 1_373_653 assert not miller_rabin(17316001 ) assert miller_rabin(17316017 ) # 25_326_001 assert not miller_rabin(3078386641 ) assert miller_rabin(3078386653 ) # 3_215_031_751 assert not miller_rabin(1713045574801 ) assert miller_rabin(1713045574819 ) # 2_152_302_898_747 assert not miller_rabin(2779799728307 ) assert miller_rabin(2779799728327 ) # 3_474_749_660_383 assert not miller_rabin(113850023909441 ) assert miller_rabin(113850023909527 ) # 341_550_071_728_321 assert not miller_rabin(1275041018848804351 ) assert miller_rabin(1275041018848804391 ) # 3_825_123_056_546_413_051 assert not miller_rabin(79666464458507787791867 ) assert miller_rabin(79666464458507787791951 ) # 318_665_857_834_031_151_167_461 assert not miller_rabin(552840677446647897660333 ) assert miller_rabin(552840677446647897660359 ) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
700
"""simple docstring""" import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowercase ( lowerCAmelCase__ : Optional[int] ) -> int: monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pytest.fixture def lowercase ( lowerCAmelCase__ : Any ) -> Any: class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): __a = metric_id class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Any = [MetricMock(__SCREAMING_SNAKE_CASE ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']] def __UpperCAmelCase ( self ): return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() ) @pytest.mark.parametrize( '''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple ) -> Optional[int]: if "tmp_path" in args: __a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(lowerCAmelCase__ , match='''https://huggingface.co/docs/evaluate''' ): func(*lowerCAmelCase__ )
65
0
"""simple docstring""" import torch from diffusers import StableDiffusionPipeline lowercase_ = "path-to-your-trained-model" lowercase_ = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to("cuda") lowercase_ = "A photo of sks dog in a bucket" lowercase_ = pipe(prompt, num_inference_steps=5_0, guidance_scale=7.5).images[0] image.save("dog-bucket.png")
701
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> int: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or number < 0: raise ValueError('''Input must be a non-negative integer''' ) __a = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer lowercase_ : Any = logging.get_logger(__name__) lowercase_ : Tuple = {'vocab_file': 'vocab.txt'} lowercase_ : Any = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } lowercase_ : int = { 'YituTech/conv-bert-base': 5_1_2, 'YituTech/conv-bert-medium-small': 5_1_2, 'YituTech/conv-bert-small': 5_1_2, } lowercase_ : int = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class __lowerCAmelCase ( snake_case__ ): '''simple docstring''' __UpperCAmelCase : Tuple = VOCAB_FILES_NAMES __UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Dict = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Dict = ConvBertTokenizer def __init__( self , _a=None , _a=None , _a=True , _a="[UNK]" , _a="[SEP]" , _a="[PAD]" , _a="[CLS]" , _a="[MASK]" , _a=True , _a=None , **_a , ): super().__init__( UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenize_chinese_chars=UpperCAmelCase_ , strip_accents=UpperCAmelCase_ , **UpperCAmelCase_ , ) __a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCAmelCase_ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCAmelCase_ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCAmelCase_ ) != tokenize_chinese_chars ): __a = getattr(UpperCAmelCase_ , normalizer_state.pop('''type''' ) ) __a = do_lower_case __a = strip_accents __a = tokenize_chinese_chars __a = normalizer_class(**UpperCAmelCase_ ) __a = do_lower_case def __UpperCAmelCase ( self , _a , _a=None ): __a = [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 , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCAmelCase ( self , _a , _a = None ): __a = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ )
702
"""simple docstring""" import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[Any] ) -> str: assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int ) -> Tuple: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( '''features''' , [ None, {'''text''': '''string'''}, {'''text''': '''int32'''}, {'''text''': '''float32'''}, ] , ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Union[str, Any] ) -> Optional[int]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) __a = TextDatasetReader(lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict ) -> Optional[Any]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , split=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any] ) -> Dict: if issubclass(lowerCAmelCase__ , lowerCAmelCase__ ): __a = text_path elif issubclass(lowerCAmelCase__ , lowerCAmelCase__ ): __a = [text_path] __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Union[str, Any]=("train",) ) -> Optional[Any]: assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) for split in splits: __a = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any] ) -> Union[str, Any]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a = TextDatasetReader({'''train''': text_path} , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( '''features''' , [ None, {'''text''': '''string'''}, {'''text''': '''int32'''}, {'''text''': '''float32'''}, ] , ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] ) -> str: __a = tmp_path / '''cache''' # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" __a = {'''text''': '''string'''} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) __a = TextDatasetReader({'''train''': text_path} , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple ) -> Dict: if split: __a = {split: text_path} else: __a = '''train''' __a = {'''train''': text_path, '''test''': text_path} __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() )
65
0
def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : List[str] ) -> float: if principal <= 0: raise Exception('''Principal borrowed must be > 0''' ) if rate_per_annum < 0: raise Exception('''Rate of interest must be >= 0''' ) if years_to_repay <= 0 or not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''Years to repay must be an integer > 0''' ) # Yearly rate is divided by 12 to get monthly rate __a = rate_per_annum / 12 # Years to repay is multiplied by 12 to get number of payments as payment is monthly __a = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
703
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES lowercase_ = '''tiny-wmt19-en-ru''' # Build # borrowed from a test lowercase_ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] lowercase_ = dict(zip(vocab, range(len(vocab)))) lowercase_ = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ = Path(tmpdirname) lowercase_ = build_dir / VOCAB_FILES_NAMES['''src_vocab_file'''] lowercase_ = build_dir / VOCAB_FILES_NAMES['''tgt_vocab_file'''] lowercase_ = build_dir / VOCAB_FILES_NAMES['''merges_file'''] with open(src_vocab_file, "w") as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, "w") as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, "w") as fp: fp.write("\n".join(merges)) lowercase_ = FSMTTokenizer( langs=["en", "ru"], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) lowercase_ = FSMTConfig( langs=["ru", "en"], src_vocab_size=1_0_0_0, tgt_vocab_size=1_0_0_0, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) lowercase_ = FSMTForConditionalGeneration(config) print(F'''num of params {tiny_model.num_parameters()}''') # Test lowercase_ = tokenizer(["Making tiny model"], return_tensors="pt") lowercase_ = tiny_model(**batch) print("test output:", len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F'''Generated {mname_tiny}''') # Upload # transformers-cli upload tiny-wmt19-en-ru
704
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir("fixtures/test_sentencepiece_bpe_char.model") @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = SpeechTaTokenizer __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = True def __UpperCAmelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing __a = SpeechTaTokenizer(_a ) __a = AddedToken('''<mask>''' , lstrip=_a , rstrip=_a ) __a = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self , _a ): __a = '''this is a test''' __a = '''this is a test''' return input_text, output_text def __UpperCAmelCase ( self , _a , _a=False , _a=20 , _a=5 ): __a , __a = self.get_input_output_texts(_a ) __a = tokenizer.encode(_a , add_special_tokens=_a ) __a = tokenizer.decode(_a , clean_up_tokenization_spaces=_a ) return text, ids def __UpperCAmelCase ( self ): __a = '''<pad>''' __a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def __UpperCAmelCase ( self ): __a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(_a ) , 81 ) def __UpperCAmelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __UpperCAmelCase ( self ): __a = self.get_tokenizers(do_lower_case=_a ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) __a = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] __a = tokenizer.add_tokens(_a ) __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) self.assertEqual(_a , _a ) self.assertEqual(_a , len(_a ) ) self.assertEqual(_a , all_size + len(_a ) ) __a = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=_a ) self.assertGreaterEqual(len(_a ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) __a = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} __a = tokenizer.add_special_tokens(_a ) __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) self.assertEqual(_a , _a ) self.assertEqual(_a , len(_a ) ) self.assertEqual(_a , all_size_a + len(_a ) ) __a = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=_a ) self.assertGreaterEqual(len(_a ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = self.get_tokenizer() __a = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(_a , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) __a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) __a = tokenizer.convert_tokens_to_ids(_a ) # fmt: off self.assertListEqual(_a , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on __a = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def __UpperCAmelCase ( self ): # Use custom sequence because this tokenizer does not handle numbers. __a = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off __a = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=_a , )
65
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_vit_mae": ["VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMAEConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMAEForPreTraining", "ViTMAELayer", "ViTMAEModel", "ViTMAEPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TFViTMAEForPreTraining", "TFViTMAEModel", "TFViTMAEPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
705
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = ['input_features', 'attention_mask'] def __init__( self , _a=80 , _a=16_000 , _a=0.0 , _a=10 , _a=25 , _a="hamming_window" , _a=3_2768.0 , _a=0.97 , _a=1.0 , _a=True , _a=True , _a=False , **_a , ): super().__init__(feature_size=_a , sampling_rate=_a , padding_value=_a , **_a ) __a = feature_size __a = sampling_rate __a = padding_value __a = hop_length __a = win_length __a = frame_signal_scale __a = preemphasis_coeff __a = mel_floor __a = normalize_means __a = normalize_vars __a = win_function __a = return_attention_mask __a = win_length * sampling_rate // 1_000 __a = hop_length * sampling_rate // 1_000 __a = optimal_fft_length(self.sample_size ) __a = (self.n_fft // 2) + 1 def __UpperCAmelCase ( self , _a ): if self.win_function == "hamming_window": __a = window_function(window_length=self.sample_size , name=self.win_function , periodic=_a ) else: __a = window_function(window_length=self.sample_size , name=self.win_function ) __a = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) __a = spectrogram( one_waveform * self.frame_signal_scale , window=_a , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=_a , preemphasis=self.preemphasis_coeff , mel_filters=_a , mel_floor=self.mel_floor , log_mel='''log''' , ) return msfc_features.T def __UpperCAmelCase ( self , _a , _a , _a ): # make sure we normalize float32 arrays if self.normalize_means: __a = x[:input_length].mean(axis=0 ) __a = np.subtract(_a , _a ) if self.normalize_vars: __a = x[:input_length].std(axis=0 ) __a = np.divide(_a , _a ) if input_length < x.shape[0]: __a = padding_value # make sure array is in float32 __a = x.astype(np.floataa ) return x def __UpperCAmelCase ( self , _a , _a = None ): __a = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(_a , _a , self.padding_value ) for x, n in zip(_a , _a )] def __call__( self , _a , _a = False , _a = None , _a = False , _a = None , _a = None , _a = None , _a = None , **_a , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with''' f''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __a = isinstance(_a , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) __a = is_batched_numpy or ( isinstance(_a , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __a = [np.asarray(_a , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_a , np.ndarray ): __a = np.asarray(_a , dtype=np.floataa ) elif isinstance(_a , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __a = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __a = [raw_speech] # extract fbank features __a = [self._extract_mfsc_features(_a ) for one_waveform in raw_speech] # convert into correct format for padding __a = BatchFeature({'''input_features''': features} ) __a = self.pad( _a , padding=_a , max_length=_a , truncation=_a , pad_to_multiple_of=_a , return_attention_mask=_a , **_a , ) # make sure list is in array format __a = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , _a ): __a = [np.asarray(_a , dtype=np.floataa ) for feature in input_features] __a = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __a = [np.asarray(_a , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: __a = ( np.array(_a , dtype=np.intaa ) if self._get_padding_strategies(_a , max_length=_a ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) __a = self.normalize( padded_inputs['''input_features'''] , attention_mask=_a ) if return_tensors is not None: __a = padded_inputs.convert_to_tensors(_a ) return padded_inputs
65
0
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "Helsinki-NLP/opus-mt-en-de": "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json", # See all Marian models at https://huggingface.co/models?filter=marian } class __lowerCAmelCase ( __lowerCamelCase ): '''simple docstring''' __UpperCAmelCase : int = 'marian' __UpperCAmelCase : List[Any] = ['past_key_values'] __UpperCAmelCase : List[str] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , _a=58_101 , _a=None , _a=1_024 , _a=12 , _a=4_096 , _a=16 , _a=12 , _a=4_096 , _a=16 , _a=0.0 , _a=0.0 , _a=True , _a=True , _a="gelu" , _a=1_024 , _a=0.1 , _a=0.0 , _a=0.0 , _a=0.02 , _a=58_100 , _a=False , _a=58_100 , _a=0 , _a=0 , _a=True , **_a , ): __a = vocab_size __a = decoder_vocab_size or vocab_size __a = max_position_embeddings __a = d_model __a = encoder_ffn_dim __a = encoder_layers __a = encoder_attention_heads __a = decoder_ffn_dim __a = decoder_layers __a = decoder_attention_heads __a = dropout __a = attention_dropout __a = activation_dropout __a = activation_function __a = init_std __a = encoder_layerdrop __a = decoder_layerdrop __a = use_cache __a = encoder_layers __a = scale_embedding # scale factor will be sqrt(d_model) if True __a = share_encoder_decoder_embeddings super().__init__( pad_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , forced_eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) class __lowerCAmelCase ( __lowerCamelCase ): '''simple docstring''' @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs def __UpperCAmelCase ( self ): if self.task in ["default", "seq2seq-lm"]: __a = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ] ) if self.use_past: __a = {0: 'batch'} __a = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __a = {0: 'batch', 1: 'decoder_sequence'} __a = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(UpperCAmelCase_ , direction='''inputs''' ) elif self.task == "causal-lm": # TODO: figure this case out. __a = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ] ) if self.use_past: __a = self.num_layers for i in range(UpperCAmelCase_ ): __a = {0: 'batch', 2: 'past_sequence + sequence'} __a = {0: 'batch', 2: 'past_sequence + sequence'} else: __a = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''decoder_input_ids''', {0: '''batch''', 1: '''decoder_sequence'''}), ('''decoder_attention_mask''', {0: '''batch''', 1: '''decoder_sequence'''}), ] ) return common_inputs @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs def __UpperCAmelCase ( self ): if self.task in ["default", "seq2seq-lm"]: __a = super().outputs else: __a = super(UpperCAmelCase_ , self ).outputs if self.use_past: __a = self.num_layers for i in range(UpperCAmelCase_ ): __a = {0: 'batch', 2: 'past_sequence + sequence'} __a = {0: 'batch', 2: 'past_sequence + sequence'} return common_outputs def __UpperCAmelCase ( self , _a , _a = -1 , _a = -1 , _a = False , _a = None , ): __a = self._generate_dummy_inputs_for_encoder_and_decoder( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # Generate decoder inputs __a = seq_length if not self.use_past else 1 __a = self._generate_dummy_inputs_for_encoder_and_decoder( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) __a = {f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()} __a = dict(**UpperCAmelCase_ , **UpperCAmelCase_ ) if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch __a = common_inputs['input_ids'].shape __a = common_inputs['decoder_input_ids'].shape[1] __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = decoder_seq_length + 3 __a = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __a = torch.cat( [common_inputs['''decoder_attention_mask'''], torch.ones(UpperCAmelCase_ , UpperCAmelCase_ )] , dim=1 ) __a = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __a = self.num_layers __a = min(UpperCAmelCase_ , UpperCAmelCase_ ) __a = max(UpperCAmelCase_ , UpperCAmelCase_ ) - min_num_layers __a = 'encoder' if num_encoder_layers > num_decoder_layers else 'decoder' for _ in range(UpperCAmelCase_ ): common_inputs["past_key_values"].append( ( torch.zeros(UpperCAmelCase_ ), torch.zeros(UpperCAmelCase_ ), torch.zeros(UpperCAmelCase_ ), torch.zeros(UpperCAmelCase_ ), ) ) # TODO: test this. __a = encoder_shape if remaining_side_name == 'encoder' else decoder_shape for _ in range(UpperCAmelCase_ , UpperCAmelCase_ ): common_inputs["past_key_values"].append((torch.zeros(UpperCAmelCase_ ), torch.zeros(UpperCAmelCase_ )) ) return common_inputs def __UpperCAmelCase ( self , _a , _a = -1 , _a = -1 , _a = False , _a = None , ): __a = self._generate_dummy_inputs_for_encoder_and_decoder( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch __a = common_inputs['input_ids'].shape # Not using the same length for past_key_values __a = seqlen + 2 __a = self.num_layers __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = common_inputs['attention_mask'].dtype __a = torch.cat( [common_inputs['''attention_mask'''], torch.ones(UpperCAmelCase_ , UpperCAmelCase_ , dtype=UpperCAmelCase_ )] , dim=1 ) __a = [ (torch.zeros(UpperCAmelCase_ ), torch.zeros(UpperCAmelCase_ )) for _ in range(UpperCAmelCase_ ) ] return common_inputs def __UpperCAmelCase ( self , _a , _a = -1 , _a = -1 , _a = False , _a = None , ): # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __a = compute_effective_axis_dimension( UpperCAmelCase_ , 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 __a = tokenizer.num_special_tokens_to_add(UpperCAmelCase_ ) __a = compute_effective_axis_dimension( UpperCAmelCase_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCAmelCase_ ) # Generate dummy inputs according to compute batch and sequence __a = [' '.join([tokenizer.unk_token] ) * seq_length] * batch_size __a = dict(tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ ) ) return common_inputs def __UpperCAmelCase ( self , _a , _a = -1 , _a = -1 , _a = False , _a = None , ): if self.task in ["default", "seq2seq-lm"]: __a = self._generate_dummy_inputs_for_default_and_seqaseq_lm( UpperCAmelCase_ , batch_size=UpperCAmelCase_ , seq_length=UpperCAmelCase_ , is_pair=UpperCAmelCase_ , framework=UpperCAmelCase_ ) else: __a = self._generate_dummy_inputs_for_causal_lm( UpperCAmelCase_ , batch_size=UpperCAmelCase_ , seq_length=UpperCAmelCase_ , is_pair=UpperCAmelCase_ , framework=UpperCAmelCase_ ) return common_inputs def __UpperCAmelCase ( self , _a , _a , _a , _a ): if self.task in ["default", "seq2seq-lm"]: __a = super()._flatten_past_key_values_(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) else: __a = super(UpperCAmelCase_ , self )._flatten_past_key_values_( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) @property def __UpperCAmelCase ( self ): return 1E-4
706
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env' ) @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue_model_parallelism.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_6_0_0, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_6_0_0, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, ] ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=_a , ) assert hasattr(self , '''env''' ) def __UpperCAmelCase ( self , _a ): # configuration for running training on smdistributed Model Parallel __a = { '''enabled''': True, '''processes_per_host''': 8, } __a = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __a = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __a = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=_a , instance_type=self.instance_type , debugger_hook_config=_a , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 500, } , metric_definitions=self.env.metric_definitions , distribution=_a , py_version='''py36''' , ) def __UpperCAmelCase ( self , _a ): TrainingJobAnalytics(_a ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __UpperCAmelCase ( self , _a ): # create estimator __a = self.create_estimator(_a ) # run training estimator.fit() # result dataframe __a = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __a = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 999_999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , _a )
65
0
"""simple docstring""" import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: __a = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg' __a = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ).convert('''RGB''' ) __a = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73) , (0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11) ), ] ) __a = transform(lowerCAmelCase__ ).unsqueeze(0 ).to(lowerCAmelCase__ ) return image def lowercase ( lowerCAmelCase__ : Tuple ) -> int: if "visual_encoder" in key: __a = re.sub('''visual_encoder*''' , '''vision_model.encoder''' , lowerCAmelCase__ ) if "blocks" in key: __a = re.sub(r'''blocks''' , '''layers''' , lowerCAmelCase__ ) if "attn" in key: __a = re.sub(r'''attn''' , '''self_attn''' , lowerCAmelCase__ ) if "norm1" in key: __a = re.sub(r'''norm1''' , '''layer_norm1''' , lowerCAmelCase__ ) if "norm2" in key: __a = re.sub(r'''norm2''' , '''layer_norm2''' , lowerCAmelCase__ ) if "encoder.norm" in key: __a = re.sub(r'''encoder.norm''' , '''post_layernorm''' , lowerCAmelCase__ ) if "encoder.patch_embed.proj" in key: __a = re.sub(r'''encoder.patch_embed.proj''' , '''embeddings.patch_embedding''' , lowerCAmelCase__ ) if "encoder.pos_embed" in key: __a = re.sub(r'''encoder.pos_embed''' , '''embeddings.position_embedding''' , lowerCAmelCase__ ) if "encoder.cls_token" in key: __a = re.sub(r'''encoder.cls_token''' , '''embeddings.class_embedding''' , lowerCAmelCase__ ) if "self_attn" in key: __a = re.sub(r'''self_attn.proj''' , '''self_attn.projection''' , lowerCAmelCase__ ) return key @torch.no_grad() def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str=None ) -> str: if config_path is not None: __a = BlipConfig.from_pretrained(lowerCAmelCase__ ) else: __a = BlipConfig(projection_dim=512 , text_config={} , vision_config={} ) __a = BlipForConditionalGeneration(lowerCAmelCase__ ).eval() __a = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth' __a = blip_decoder(pretrained=lowerCAmelCase__ , image_size=384 , vit='''base''' ) __a = pt_model.eval() __a = pt_model.state_dict() for key in modified_state_dict.copy(): __a = modified_state_dict.pop(lowerCAmelCase__ ) __a = rename_key(lowerCAmelCase__ ) __a = value hf_model.load_state_dict(lowerCAmelCase__ ) __a = 384 __a = load_demo_image(image_size=lowerCAmelCase__ , device='''cpu''' ) __a = BertTokenizer.from_pretrained('''bert-base-uncased''' ) __a = tokenizer(['''a picture of'''] ).input_ids __a = hf_model.generate(lowerCAmelCase__ , lowerCAmelCase__ ) assert out[0].tolist() == [30522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] __a = hf_model.generate(lowerCAmelCase__ ) assert out[0].tolist() == [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(lowerCAmelCase__ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' __a = ( 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth' ) __a = blip_vqa(pretrained=lowerCAmelCase__ , image_size=lowerCAmelCase__ , vit='''base''' ) vqa_model.eval() __a = vqa_model.state_dict() for key in modified_state_dict.copy(): __a = modified_state_dict.pop(lowerCAmelCase__ ) __a = rename_key(lowerCAmelCase__ ) __a = value __a = BlipForQuestionAnswering(lowerCAmelCase__ ) hf_vqa_model.load_state_dict(lowerCAmelCase__ ) __a = ['How many dogs are in this image?'] __a = tokenizer(lowerCAmelCase__ , return_tensors='''pt''' ).input_ids __a = hf_vqa_model.generate(lowerCAmelCase__ , lowerCAmelCase__ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '''_vqa''' ) __a = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth' __a = blip_itm(pretrained=lowerCAmelCase__ , image_size=lowerCAmelCase__ , vit='''base''' ) itm_model.eval() __a = itm_model.state_dict() for key in modified_state_dict.copy(): __a = modified_state_dict.pop(lowerCAmelCase__ ) __a = rename_key(lowerCAmelCase__ ) __a = value __a = BlipForImageTextRetrieval(lowerCAmelCase__ ) __a = ['A picture of a woman with a dog sitting in a beach'] __a = tokenizer( lowerCAmelCase__ , return_tensors='''pt''' , padding='''max_length''' , truncation=lowerCAmelCase__ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(lowerCAmelCase__ ) hf_itm_model.eval() __a = hf_itm_model(lowerCAmelCase__ , lowerCAmelCase__ , use_itm_head=lowerCAmelCase__ ) __a = hf_itm_model(lowerCAmelCase__ , lowerCAmelCase__ , use_itm_head=lowerCAmelCase__ ) assert out[0].item() == 0.21_10_68_74_94_27_79_54 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_56_98_84_53_86_50_51_27 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '''_itm''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") lowercase_ = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
707
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
65
0
"""simple docstring""" import math import sys def lowercase ( lowerCAmelCase__ : int ) -> int: '''simple docstring''' if number != int(__A ): raise ValueError('''the value of input must be a natural number''' ) if number < 0: raise ValueError('''the value of input must not be a negative number''' ) if number == 0: return 1 __a = [-1] * (number + 1) __a = 0 for i in range(1 , number + 1 ): __a = sys.maxsize __a = int(math.sqrt(__A ) ) for j in range(1 , root + 1 ): __a = 1 + answers[i - (j**2)] __a = min(__A , __A ) __a = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
708
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable lowercase_ = {"configuration_gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["GPTNeoXTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXForCausalLM", "GPTNeoXForQuestionAnswering", "GPTNeoXForSequenceClassification", "GPTNeoXForTokenClassification", "GPTNeoXLayer", "GPTNeoXModel", "GPTNeoXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
65
0
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py lowercase_ = 'src/diffusers' # Matches is_xxx_available() lowercase_ = re.compile(r"is\_([a-z_]*)_available\(\)") # Matches from xxx import bla lowercase_ = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") lowercase_ = '\n{0} = None\n' lowercase_ = '\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, {1})\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, {1})\n' lowercase_ = '\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n' def lowercase ( lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = _re_backend.findall(__lowerCAmelCase ) if len(__lowerCAmelCase ) == 0: return None return "_and_".join(__lowerCAmelCase ) def lowercase ( ) -> Any: with open(os.path.join(__lowerCAmelCase , '''__init__.py''' ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __a = f.readlines() # Get to the point we do the actual imports for type checking __a = 0 __a = {} # Go through the end of the file while line_index < len(__lowerCAmelCase ): # If the line contains is_backend_available, we grab all objects associated with the `else` block __a = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('''else:''' ): line_index += 1 line_index += 1 __a = [] # Until we unindent, add backend objects to the list while line_index < len(__lowerCAmelCase ) and len(lines[line_index] ) > 1: __a = lines[line_index] __a = _re_single_line_import.search(__lowerCAmelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(__lowerCAmelCase ) > 0: __a = objects else: line_index += 1 return backend_specific_objects def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict ) -> Union[str, Any]: if name.isupper(): return DUMMY_CONSTANT.format(__lowerCAmelCase ) elif name.islower(): return DUMMY_FUNCTION.format(__lowerCAmelCase , __lowerCAmelCase ) else: return DUMMY_CLASS.format(__lowerCAmelCase , __lowerCAmelCase ) def lowercase ( lowerCAmelCase__ : Optional[int]=None ) -> Union[str, Any]: if backend_specific_objects is None: __a = read_init() # For special correspondence backend to module name as used in the function requires_modulename __a = {} for backend, objects in backend_specific_objects.items(): __a = '''[''' + ''', '''.join(f'''"{b}"''' for b in backend.split('''_and_''' ) ) + ''']''' __a = '''# This file is autogenerated by the command `make fix-copies`, do not edit.\n''' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(__lowerCAmelCase , __lowerCAmelCase ) for o in objects] ) __a = dummy_file return dummy_files def lowercase ( lowerCAmelCase__ : List[str]=False ) -> List[Any]: __a = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py __a = {'''torch''': '''pt'''} # Locate actual dummy modules and read their content. __a = os.path.join(__lowerCAmelCase , '''utils''' ) __a = { backend: os.path.join(__lowerCAmelCase , f'''dummy_{short_names.get(__lowerCAmelCase , __lowerCAmelCase )}_objects.py''' ) for backend in dummy_files.keys() } __a = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(__lowerCAmelCase ): with open(__lowerCAmelCase , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __a = f.read() else: __a = '''''' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( f'''Updating diffusers.utils.dummy_{short_names.get(__lowerCAmelCase , __lowerCAmelCase )}_objects.py as the main ''' '''__init__ has new objects.''' ) with open(dummy_file_paths[backend] , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( '''The main __init__ has objects that are not present in ''' f'''diffusers.utils.dummy_{short_names.get(__lowerCAmelCase , __lowerCAmelCase )}_objects.py. Run `make fix-copies` ''' '''to fix this.''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowercase_ = parser.parse_args() check_dummies(args.fix_and_overwrite)
709
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=2 , _a=8 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=16 , _a=5 , _a=2 , _a=36 , _a="gelu" , _a=0.0 , _a=0.0 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self ): __a = self.get_config() __a = 300 return config def __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraModel(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a ) __a = model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = MraModel(_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , ) __a = model( _a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , ) __a = model(_a , attention_mask=_a , token_type_ids=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraForMaskedLM(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraForQuestionAnswering(config=_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , token_type_ids=_a , start_positions=_a , end_positions=_a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MraForSequenceClassification(_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MraForTokenClassification(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_choices __a = MraForMultipleChoice(config=_a ) model.to(_a ) model.eval() __a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) __UpperCAmelCase : str = False __UpperCAmelCase : Any = False __UpperCAmelCase : List[Any] = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Dict = () def __UpperCAmelCase ( self ): __a = MraModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a = type self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MraModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip(reason='''MRA does not output attentions''' ) def __UpperCAmelCase ( self ): return @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = MraModel.from_pretrained('''uw-madison/mra-base-512-4''' ) __a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4''' ) __a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = 50_265 __a = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3''' ) __a = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = 50_265 __a = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
65
0
"""simple docstring""" from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. lowercase_ = 1_0 def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str ) -> int: for i in range(lowerCamelCase__ , lowerCamelCase__ ): if array[i] == target: return i return -1 def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Any ) -> int: __a = 0 __a = len(lowerCamelCase__ ) while left <= right: if right - left < precision: return lin_search(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __a = (left + right) // 3 + 1 __a = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: __a = one_third - 1 elif array[two_third] < target: __a = two_third + 1 else: __a = one_third + 1 __a = two_third - 1 else: return -1 def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any ) -> int: if left < right: if right - left < precision: return lin_search(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __a = (left + right) // 3 + 1 __a = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(lowerCamelCase__ , one_third - 1 , lowerCamelCase__ , lowerCamelCase__ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , lowerCamelCase__ , lowerCamelCase__ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = input("Enter numbers separated by comma:\n").strip() lowercase_ = [int(item.strip()) for item in user_input.split(",")] assert collection == sorted(collection), F"List must be ordered.\n{collection}." lowercase_ = int(input("Enter the number to be found in the list:\n").strip()) lowercase_ = ite_ternary_search(collection, target) lowercase_ = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(F'''Iterative search: {target} found at positions: {resulta}''') print(F'''Recursive search: {target} found at positions: {resulta}''') else: print("Not found")
710
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> list[str]: if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number_of_bytes!''' ) __a = number_of_bytes // partitions __a = [] for i in range(lowerCAmelCase__ ): __a = i * bytes_per_partition + 1 __a = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=3 , _a=32 , _a=3 , _a=10 , _a=[8, 16, 32, 64] , _a=[1, 1, 2, 1] , _a=True , _a=True , _a="relu" , _a=3 , _a=None , _a=["stage2", "stage3", "stage4"] , _a=[2, 3, 4] , _a=1 , ): __a = parent __a = batch_size __a = image_size __a = num_channels __a = embeddings_size __a = hidden_sizes __a = depths __a = is_training __a = use_labels __a = hidden_act __a = num_labels __a = scope __a = len(__A ) __a = out_features __a = out_indices __a = num_groups def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): return BitConfig( 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 , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = BitModel(config=__A ) model.to(__A ) model.eval() __a = model(__A ) 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 , _a , _a , _a ): __a = self.num_labels __a = BitForImageClassification(__A ) model.to(__A ) model.eval() __a = model(__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = BitBackbone(config=__A ) model.to(__A ) model.eval() __a = model(__A ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None __a = None __a = BitBackbone(config=__A ) model.to(__A ) model.eval() __a = model(__A ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a = config_and_inputs __a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Tuple = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () __UpperCAmelCase : Tuple = ( {'feature-extraction': BitModel, 'image-classification': BitForImageClassification} if is_torch_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : List[str] = False __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): __a = BitModelTester(self ) __a = ConfigTester(self , config_class=__A , has_text_modality=__A ) def __UpperCAmelCase ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __UpperCAmelCase ( self ): return @unittest.skip(reason='''Bit does not output attentions''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''Bit does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''Bit does not support input and output embeddings''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__A ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["pixel_values"] self.assertListEqual(arg_names[:1] , __A ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__A ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(config=__A ) for name, module in model.named_modules(): if isinstance(__A , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __a = model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__A , __A ) ) __a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __a = self.model_tester.num_stages self.assertEqual(len(__A ) , expected_num_stages + 1 ) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __a = self.model_tester.prepare_config_and_inputs_for_common() __a = ["preactivation", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: __a = layer_type __a = True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(__A , __A , __A ) @unittest.skip(reason='''Bit does not use feedforward chunking''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) @slow def __UpperCAmelCase ( self ): for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = BitModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def lowercase ( ) -> Tuple: __a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCAmelCase ( self ): return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): __a = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(__A ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__A , return_tensors='''pt''' ).to(__A ) # forward pass with torch.no_grad(): __a = model(**__A ) # verify the logits __a = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , __A ) __a = torch.tensor([[-0.6526, -0.5263, -1.4398]] ).to(__A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __A , atol=1E-4 ) ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = (BitBackbone,) if is_torch_available() else () __UpperCAmelCase : str = BitConfig __UpperCAmelCase : Dict = False def __UpperCAmelCase ( self ): __a = BitModelTester(self )
711
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> list: __a = len(lowerCAmelCase__ ) __a = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): __a = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" import os import sys import unittest lowercase_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path lowercase_ = os.path.join(git_repo_path, "src", "diffusers") class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = find_backend(''' if not is_torch_available():''' ) self.assertEqual(_a , '''torch''' ) # backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") # self.assertEqual(backend_with_underscore, "tensorflow_text") __a = find_backend(''' if not (is_torch_available() and is_transformers_available()):''' ) self.assertEqual(_a , '''torch_and_transformers''' ) # double_backend_with_underscore = find_backend( # " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" # ) # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") __a = find_backend( ''' if not (is_torch_available() and is_transformers_available() and is_onnx_available()):''' ) self.assertEqual(_a , '''torch_and_transformers_and_onnx''' ) def __UpperCAmelCase ( self ): __a = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('''torch''' , _a ) self.assertIn('''torch_and_transformers''' , _a ) self.assertIn('''flax_and_transformers''' , _a ) self.assertIn('''torch_and_transformers_and_onnx''' , _a ) # Likewise, we can't assert on the exact content of a key self.assertIn('''UNet2DModel''' , objects['''torch'''] ) self.assertIn('''FlaxUNet2DConditionModel''' , objects['''flax'''] ) self.assertIn('''StableDiffusionPipeline''' , objects['''torch_and_transformers'''] ) self.assertIn('''FlaxStableDiffusionPipeline''' , objects['''flax_and_transformers'''] ) self.assertIn('''LMSDiscreteScheduler''' , objects['''torch_and_scipy'''] ) self.assertIn('''OnnxStableDiffusionPipeline''' , objects['''torch_and_transformers_and_onnx'''] ) def __UpperCAmelCase ( self ): __a = create_dummy_object('''CONSTANT''' , '''\'torch\'''' ) self.assertEqual(_a , '''\nCONSTANT = None\n''' ) __a = create_dummy_object('''function''' , '''\'torch\'''' ) self.assertEqual( _a , '''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' ) __a = """ class FakeClass(metaclass=DummyObject): _backends = 'torch' def __init__(self, *args, **kwargs): requires_backends(self, 'torch') @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, 'torch') @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, 'torch') """ __a = create_dummy_object('''FakeClass''' , '''\'torch\'''' ) self.assertEqual(_a , _a ) def __UpperCAmelCase ( self ): __a = """# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, [\"torch\"]) class FakeClass(metaclass=DummyObject): _backends = [\"torch\"] def __init__(self, *args, **kwargs): requires_backends(self, [\"torch\"]) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, [\"torch\"]) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, [\"torch\"]) """ __a = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} ) self.assertEqual(dummy_files['''torch'''] , _a )
712
"""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 lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} lowercase_ = { "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" ), }, } lowercase_ = { "allenai/longformer-base-4096": 4_0_9_6, "allenai/longformer-large-4096": 4_0_9_6, "allenai/longformer-large-4096-finetuned-triviaqa": 4_0_9_6, "allenai/longformer-base-4096-extra.pos.embd.only": 4_0_9_6, "allenai/longformer-large-4096-extra.pos.embd.only": 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowercase ( ) -> Union[str, Any]: __a = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __a = bs[:] __a = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCAmelCase__ ) cs.append(2**8 + n ) n += 1 __a = [chr(lowerCAmelCase__ ) for n in cs] return dict(zip(lowerCAmelCase__ , lowerCAmelCase__ ) ) def lowercase ( lowerCAmelCase__ : Tuple ) -> Tuple: __a = set() __a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __a = char return pairs class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = VOCAB_FILES_NAMES __UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Union[str, Any] = ['input_ids', 'attention_mask'] def __init__( self , _a , _a , _a="replace" , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=False , **_a , ): __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else bos_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else sep_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else cls_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( errors=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , **_a , ) with open(_a , encoding='''utf-8''' ) as vocab_handle: __a = json.load(_a ) __a = {v: k for k, v in self.encoder.items()} __a = errors # how to handle errors in decoding __a = bytes_to_unicode() __a = {v: k for k, v in self.byte_encoder.items()} with open(_a , encoding='''utf-8''' ) as merges_handle: __a = merges_handle.read().split('''\n''' )[1:-1] __a = [tuple(merge.split() ) for merge in bpe_merges] __a = dict(zip(_a , range(len(_a ) ) ) ) __a = {} __a = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __a = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def __UpperCAmelCase ( self ): return len(self.encoder ) def __UpperCAmelCase ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def __UpperCAmelCase ( self , _a ): if token in self.cache: return self.cache[token] __a = tuple(_a ) __a = get_pairs(_a ) if not pairs: return token while True: __a = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __a , __a = bigram __a = [] __a = 0 while i < len(_a ): try: __a = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __a = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __a = tuple(_a ) __a = new_word if len(_a ) == 1: break else: __a = get_pairs(_a ) __a = ''' '''.join(_a ) __a = word return word def __UpperCAmelCase ( self , _a ): __a = [] for token in re.findall(self.pat , _a ): __a = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(''' ''' ) ) return bpe_tokens def __UpperCAmelCase ( self , _a ): return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def __UpperCAmelCase ( self , _a ): return self.decoder.get(_a ) def __UpperCAmelCase ( self , _a ): __a = ''''''.join(_a ) __a = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def __UpperCAmelCase ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_a , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '''\n''' ) __a = 0 with open(_a , '''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 _a : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __a = token_index writer.write(''' '''.join(_a ) + '''\n''' ) index += 1 return vocab_file, merge_file def __UpperCAmelCase ( self , _a , _a = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __a = [self.cls_token_id] __a = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __UpperCAmelCase ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self , _a , _a=False , **_a ): __a = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): __a = ''' ''' + text return (text, kwargs)
65
0
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "EleutherAI/gpt-neo-1.3B": "https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json", # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class __lowerCAmelCase ( _snake_case ): '''simple docstring''' __UpperCAmelCase : List[Any] = 'gpt_neo' __UpperCAmelCase : Tuple = ['past_key_values'] __UpperCAmelCase : Optional[int] = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__( self , _a=50_257 , _a=2_048 , _a=2_048 , _a=24 , _a=[[["global", "local"], 12]] , _a=16 , _a=None , _a=256 , _a="gelu_new" , _a=0.0 , _a=0.0 , _a=0.0 , _a=0.1 , _a=1E-5 , _a=0.02 , _a=True , _a=50_256 , _a=50_256 , **_a , ): __a = vocab_size __a = max_position_embeddings __a = hidden_size __a = num_layers __a = num_heads __a = intermediate_size __a = window_size __a = activation_function __a = resid_dropout __a = embed_dropout __a = attention_dropout __a = classifier_dropout __a = layer_norm_epsilon __a = initializer_range __a = use_cache __a = bos_token_id __a = eos_token_id __a = attention_types __a = self.expand_attention_types_params(_a ) if len(self.attention_layers ) != self.num_layers: raise ValueError( '''Configuration for convolutional module is incorrect. ''' '''It is required that `len(config.attention_layers)` == `config.num_layers` ''' f'''but is `len(config.attention_layers) = {len(self.attention_layers )}`, ''' f'''`config.num_layers = {self.num_layers}`. ''' '''`config.attention_layers` is prepared using `config.attention_types`. ''' '''Please verify the value of `config.attention_types` argument.''' ) super().__init__(bos_token_id=_a , eos_token_id=_a , **_a ) @staticmethod def __UpperCAmelCase ( _a ): __a = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : List[str] ) -> Tuple: import torch __a = input.size() __a = len(__UpperCAmelCase ) __a = shape[dimension] __a = torch.arange(0 , __UpperCAmelCase , __UpperCAmelCase ) __a = torch.div(sizedim - size , __UpperCAmelCase , rounding_mode='''floor''' ) + 1 __a = torch.arange(__UpperCAmelCase ) + low_indices[:min_length][:, None] __a = [slice(__UpperCAmelCase )] * rank __a = indices __a = input[s] __a = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(__UpperCAmelCase ) def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] ) -> List[Any]: import torch __a = torch.arange(1 , __UpperCAmelCase ) __a = torch.remainder(__UpperCAmelCase , __UpperCAmelCase ) __a = remainders == 0 __a = candidates[divisor_indices] __a = torch.max(__UpperCAmelCase ) return largest_divisor, torch.div(__UpperCAmelCase , __UpperCAmelCase , rounding_mode='''floor''' ) class __lowerCAmelCase ( _snake_case ): '''simple docstring''' @property def __UpperCAmelCase ( self ): __a = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: self.fill_with_past_key_values_(_a , direction='''inputs''' ) __a = {0: '''batch''', 1: '''past_sequence + sequence'''} else: __a = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def __UpperCAmelCase ( self ): return self._config.num_heads def __UpperCAmelCase ( self , _a , _a = -1 , _a = -1 , _a = False , _a = None , ): __a = super(_a , self ).generate_dummy_inputs( _a , batch_size=_a , seq_length=_a , is_pair=_a , framework=_a ) # We need to order the input in the way they appears in the forward() __a = OrderedDict({'''input_ids''': common_inputs['''input_ids''']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch __a , __a = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values __a = seqlen + 2 __a = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __a = [ (torch.zeros(_a ), torch.zeros(_a )) for _ in range(self.num_layers ) ] __a = common_inputs['''attention_mask'''] if self.use_past: __a = ordered_inputs['''attention_mask'''].dtype __a = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(_a , _a , dtype=_a )] , dim=1 ) return ordered_inputs @property def __UpperCAmelCase ( self ): return 13
713
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "unc-nlp/lxmert-base-uncased": "https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = 'lxmert' __UpperCAmelCase : str = {} def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=9_500 , _a=1_600 , _a=400 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=9 , _a=5 , _a=5 , _a=2_048 , _a=4 , _a=6.67 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=True , _a=True , **_a , ): __a = vocab_size __a = hidden_size __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = num_qa_labels __a = num_object_labels __a = num_attr_labels __a = l_layers __a = x_layers __a = r_layers __a = visual_feat_dim __a = visual_pos_dim __a = visual_loss_normalizer __a = task_matched __a = task_mask_lm __a = task_obj_predict __a = task_qa __a = visual_obj_loss __a = visual_attr_loss __a = visual_feat_loss __a = {'''vision''': r_layers, '''cross_encoder''': x_layers, '''language''': l_layers} super().__init__(**_a )
65
0
"""simple docstring""" import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_UpperCAmelCase , '''width_multiplier''' ) ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=64 , _a=2 , _a=3 , _a="swish" , _a=3 , _a=32 , _a=0.1 , _a=0.02 , _a=True , _a=True , _a=10 , _a=None , _a=0.25 , _a=0.0 , _a=0.0 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = make_divisible(512 * width_multiplier , divisor=8 ) __a = hidden_act __a = conv_kernel_size __a = output_stride __a = classifier_dropout_prob __a = use_labels __a = is_training __a = num_labels __a = initializer_range __a = scope __a = width_multiplier __a = ffn_dropout __a = attn_dropout def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = MobileViTVaModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __a = model(_UpperCAmelCase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __a = model(_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a ): __a = self.num_labels __a = MobileViTVaForSemanticSegmentation(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __a = model(_UpperCAmelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __a = model(_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Dict = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : List[str] = ( { 'feature-extraction': MobileViTVaModel, 'image-classification': MobileViTVaForImageClassification, 'image-segmentation': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : List[str] = False __UpperCAmelCase : Any = False __UpperCAmelCase : str = False def __UpperCAmelCase ( self ): __a = MobileViTVaModelTester(self ) __a = MobileViTVaConfigTester(self , config_class=_UpperCAmelCase , has_text_modality=_UpperCAmelCase ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''' ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason='''MobileViTV2 does not output attentions''' ) def __UpperCAmelCase ( self ): pass @require_torch_multi_gpu @unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_UpperCAmelCase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _UpperCAmelCase ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def __UpperCAmelCase ( self ): def check_hidden_states_output(_a , _a , _a ): __a = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase ) ) __a = outputs.hidden_states __a = 5 self.assertEqual(len(_UpperCAmelCase ) , _UpperCAmelCase ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a = 2 for i in range(len(_UpperCAmelCase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCAmelCase ) @slow def __UpperCAmelCase ( self ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MobileViTVaModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def lowercase ( ) -> str: __a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCAmelCase ( self ): return ( MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ).to( _UpperCAmelCase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=_UpperCAmelCase , return_tensors='''pt''' ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): __a = model(**_UpperCAmelCase ) # verify the logits __a = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , _UpperCAmelCase ) __a = torch.tensor([-1.6_336E00, -7.3_204E-02, -5.1_883E-01] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _UpperCAmelCase , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_UpperCAmelCase ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_UpperCAmelCase , return_tensors='''pt''' ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): __a = model(**_UpperCAmelCase ) __a = outputs.logits # verify the logits __a = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _UpperCAmelCase ) __a = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=_UpperCAmelCase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _UpperCAmelCase , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = model.to(_UpperCAmelCase ) __a = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) __a = prepare_img() __a = image_processor(images=_UpperCAmelCase , return_tensors='''pt''' ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): __a = model(**_UpperCAmelCase ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=_UpperCAmelCase , target_sizes=[(50, 60)] ) __a = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _UpperCAmelCase ) __a = image_processor.post_process_semantic_segmentation(outputs=_UpperCAmelCase ) __a = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _UpperCAmelCase )
714
"""simple docstring""" import itertools import math def lowercase ( lowerCAmelCase__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( ) -> int: __a = 2 while True: if is_prime(lowerCAmelCase__ ): yield num num += 1 def lowercase ( lowerCAmelCase__ : int = 10001 ) -> int: return next(itertools.islice(prime_generator() , nth - 1 , lowerCAmelCase__ ) ) if __name__ == "__main__": print(F'''{solution() = }''')
65
0
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = [ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] lowercase_ = [ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def lowercase ( lowerCAmelCase__ : List[Any] ) -> List[Any]: __a = torch.load(__A , map_location='''cpu''' ) return sd def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : int=rename_keys_prefix ) -> str: __a = OrderedDict() __a = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __a = key for name_pair in rename_keys_prefix: __a = new_key.replace(name_pair[0] , name_pair[1] ) __a = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __a = new_d["""cls.predictions.bias"""] return new_d @torch.no_grad() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : int ) -> int: assert ( checkpoint_path.split('''/''' )[-1] in ACCEPTABLE_CHECKPOINTS ), f'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: __a = """pretraining""" if "vcr" in checkpoint_path: __a = {"""visual_embedding_dim""": 512} elif "vqa_advanced" in checkpoint_path: __a = {"""visual_embedding_dim""": 2048} elif "vqa" in checkpoint_path: __a = {"""visual_embedding_dim""": 2048} elif "nlvr" in checkpoint_path: __a = {"""visual_embedding_dim""": 1024} else: raise NotImplementedError(f'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: __a = {"""visual_embedding_dim""": 512} __a = """multichoice""" elif "vqa_advanced" in checkpoint_path: __a = {"""visual_embedding_dim""": 2048} __a = """vqa_advanced""" elif "vqa" in checkpoint_path: __a = {"""visual_embedding_dim""": 2048, """num_labels""": 3129} __a = """vqa""" elif "nlvr" in checkpoint_path: __a = { """visual_embedding_dim""": 1024, """num_labels""": 2, } __a = """nlvr""" __a = VisualBertConfig(**__A ) # Load State Dict __a = load_state_dict(__A ) __a = get_new_dict(__A , __A ) if model_type == "pretraining": __a = VisualBertForPreTraining(__A ) elif model_type == "vqa": __a = VisualBertForQuestionAnswering(__A ) elif model_type == "nlvr": __a = VisualBertForVisualReasoning(__A ) elif model_type == "multichoice": __a = VisualBertForMultipleChoice(__A ) model.load_state_dict(__A ) # Save Checkpoints Path(__A ).mkdir(exist_ok=__A ) model.save_pretrained(__A ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") lowercase_ = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
715
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase_ = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
65
0
"""simple docstring""" from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase ( a__ ): '''simple docstring''' __UpperCAmelCase : Tuple = 'new-model' if is_tf_available(): class __lowerCAmelCase ( a__ ): '''simple docstring''' __UpperCAmelCase : Dict = NewModelConfig @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = 'bert-base-cased' __a = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __a = TFAutoModel.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __UpperCAmelCase ( self ): __a = 'bert-base-cased' __a = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __a = TFAutoModelForPreTraining.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __UpperCAmelCase ( self ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __a = TFAutoModelForCausalLM.from_pretrained(_A ) __a = TFAutoModelForCausalLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __UpperCAmelCase ( self ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __a = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __UpperCAmelCase ( self ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __a = TFAutoModelForMaskedLM.from_pretrained(_A ) __a = TFAutoModelForMaskedLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __UpperCAmelCase ( self ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __a = TFAutoModelForSeqaSeqLM.from_pretrained(_A ) __a = TFAutoModelForSeqaSeqLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __UpperCAmelCase ( self ): for model_name in ["bert-base-uncased"]: __a = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __a = TFAutoModelForSequenceClassification.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def __UpperCAmelCase ( self ): for model_name in ["bert-base-uncased"]: __a = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __a = TFAutoModelForQuestionAnswering.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow @require_tensorflow_probability def __UpperCAmelCase ( self ): for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: __a = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) __a = TFAutoModelForTableQuestionAnswering.from_pretrained(_A ) __a = TFAutoModelForTableQuestionAnswering.from_pretrained( _A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) def __UpperCAmelCase ( self ): __a = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsInstance(_A , _A ) self.assertEqual(model.num_parameters() , 14_410 ) self.assertEqual(model.num_parameters(only_trainable=_A ) , 14_410 ) def __UpperCAmelCase ( self ): __a = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsInstance(_A , _A ) self.assertEqual(model.num_parameters() , 14_410 ) self.assertEqual(model.num_parameters(only_trainable=_A ) , 14_410 ) def __UpperCAmelCase ( self ): __a = TFAutoModel.from_pretrained('''sgugger/funnel-random-tiny''' ) self.assertIsInstance(_A , _A ) __a = copy.deepcopy(model.config ) __a = ['FunnelBaseModel'] __a = TFAutoModel.from_config(_A ) self.assertIsInstance(_A , _A ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A ) __a = TFAutoModel.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def __UpperCAmelCase ( self ): try: AutoConfig.register('''new-model''' , _A ) __a = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(_A ): auto_class.register(_A , _A ) auto_class.register(_A , _A ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A ): auto_class.register(_A , _A ) # Now that the config is registered, it can be used as any other config with the auto-API __a = BertModelTester(self ).get_config() __a = NewModelConfig(**tiny_config.to_dict() ) __a = auto_class.from_config(_A ) self.assertIsInstance(_A , _A ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A ) __a = auto_class.from_pretrained(_A ) self.assertIsInstance(_A , _A ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def __UpperCAmelCase ( self ): with self.assertRaisesRegex( _A , '''bert-base is not a local folder and is not a valid model identifier''' ): __a = TFAutoModel.from_pretrained('''bert-base''' ) def __UpperCAmelCase ( self ): with self.assertRaisesRegex( _A , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __a = TFAutoModel.from_pretrained(_A , revision='''aaaaaa''' ) def __UpperCAmelCase ( self ): with self.assertRaisesRegex( _A , '''hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin''' , ): __a = TFAutoModel.from_pretrained('''hf-internal-testing/config-no-model''' ) def __UpperCAmelCase ( self ): with self.assertRaisesRegex(_A , '''Use `from_pt=True` to load this model''' ): __a = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-bert-pt-only''' ) def __UpperCAmelCase ( self ): __a = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) with RequestCounter() as counter: __a = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint __a = TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded''' ) with RequestCounter() as counter: __a = TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded''' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
716
"""simple docstring""" from sklearn.metrics import fa_score import datasets lowercase_ = "\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n" lowercase_ = "\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {'f1': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results['f1'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results['f1'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n >>> print(round(results['f1'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'f1': array([0.8, 0. , 0. ])}\n" lowercase_ = "\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def __UpperCAmelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'''] , ) def __UpperCAmelCase ( self , _a , _a , _a=None , _a=1 , _a="binary" , _a=None ): __a = fa_score( _a , _a , labels=_a , pos_label=_a , average=_a , sample_weight=_a ) return {"f1": float(_a ) if score.size == 1 else score}
65
0
"""simple docstring""" import pytest lowercase_ = "__dummy_dataset1__" lowercase_ = "\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = \"https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/\"\nURLS = {\"train\": REPO_URL + \"wikiann-bn-train.jsonl\", \"validation\": REPO_URL + \"wikiann-bn-validation.jsonl\"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n \"tokens\": datasets.Sequence(datasets.Value(\"string\")),\n \"ner_tags\": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n \"O\",\n \"B-PER\",\n \"I-PER\",\n \"B-ORG\",\n \"I-ORG\",\n \"B-LOC\",\n \"I-LOC\",\n ]\n )\n ),\n \"langs\": datasets.Sequence(datasets.Value(\"string\")),\n \"spans\": datasets.Sequence(datasets.Value(\"string\")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={\"filepath\": dl_path[\"train\"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={\"filepath\": dl_path[\"validation\"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, \"r\", encoding=\"utf-8\") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n" @pytest.fixture def lowercase ( ) -> Optional[Any]: return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def lowercase ( ) -> Optional[int]: return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : int , lowerCAmelCase__ : Union[str, Any] ) -> Optional[Any]: __a = dataset_loading_script_name __a = tmp_path / "datasets" / script_name script_dir.mkdir(parents=_lowerCamelCase ) __a = script_dir / f'''{script_name}.py''' with open(_lowerCamelCase , '''w''' ) as f: f.write(_lowerCamelCase ) return str(_lowerCamelCase )
717
"""simple docstring""" from ..utils import DummyObject, requires_backends class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = ['onnx'] def __init__( self , *_a , **_a ): requires_backends(self , ['''onnx'''] ) @classmethod def __UpperCAmelCase ( cls , *_a , **_a ): requires_backends(cls , ['''onnx'''] ) @classmethod def __UpperCAmelCase ( cls , *_a , **_a ): requires_backends(cls , ['''onnx'''] )
65
0
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowercase_ = "platform" import jax import jax.numpy as jnp from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, shift_tokens_right, ) def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[Any]=None , lowerCAmelCase__ : Optional[Any]=None , lowerCAmelCase__ : List[Any]=None , lowerCAmelCase__ : Tuple=None , lowerCAmelCase__ : List[Any]=None , lowerCAmelCase__ : Optional[int]=None , ) -> Dict: if attention_mask is None: __a = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: __a = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: __a = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __a = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __a = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=16 , _a=2 , _a=4 , _a=4 , _a="gelu" , _a=0.1 , _a=0.1 , _a=32 , _a=2 , _a=1 , _a=0 , _a=0.02 , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = eos_token_id __a = pad_token_id __a = bos_token_id __a = initializer_range def __UpperCAmelCase ( self ): __a = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) __a = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) __a = shift_tokens_right(lowerCamelCase_ , 1 , 2 ) __a = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=lowerCamelCase_ , ) __a = prepare_blenderbot_inputs_dict(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) return config, inputs_dict def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a ): __a = 20 __a = model_class_name(lowerCamelCase_ ) __a = model.encode(inputs_dict['''input_ids'''] ) __a = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __a = model.init_cache(decoder_input_ids.shape[0] , lowerCamelCase_ , lowerCamelCase_ ) __a = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) __a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __a = model.decode( decoder_input_ids[:, :-1] , lowerCamelCase_ , decoder_attention_mask=lowerCamelCase_ , past_key_values=lowerCamelCase_ , decoder_position_ids=lowerCamelCase_ , ) __a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __a = model.decode( decoder_input_ids[:, -1:] , lowerCamelCase_ , decoder_attention_mask=lowerCamelCase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowerCamelCase_ , ) __a = model.decode(lowerCamelCase_ , lowerCamelCase_ ) __a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = 20 __a = model_class_name(lowerCamelCase_ ) __a = model.encode(inputs_dict['''input_ids'''] ) __a = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __a = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __a = model.init_cache(decoder_input_ids.shape[0] , lowerCamelCase_ , lowerCamelCase_ ) __a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __a = model.decode( decoder_input_ids[:, :-1] , lowerCamelCase_ , decoder_attention_mask=lowerCamelCase_ , past_key_values=lowerCamelCase_ , decoder_position_ids=lowerCamelCase_ , ) __a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __a = model.decode( decoder_input_ids[:, -1:] , lowerCamelCase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowerCamelCase_ , decoder_position_ids=lowerCamelCase_ , ) __a = model.decode(lowerCamelCase_ , lowerCamelCase_ , decoder_attention_mask=lowerCamelCase_ ) __a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : List[Any] = 9_9 def __UpperCAmelCase ( self ): __a = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) __a = input_ids.shape[0] __a = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def __UpperCAmelCase ( self ): __a = self._get_config_and_data() __a = FlaxBlenderbotSmallForConditionalGeneration(lowerCamelCase_ ) __a = lm_model(input_ids=lowerCamelCase_ ) __a = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , lowerCamelCase_ ) def __UpperCAmelCase ( self ): __a = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) __a = FlaxBlenderbotSmallForConditionalGeneration(lowerCamelCase_ ) __a = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) __a = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) __a = lm_model(input_ids=lowerCamelCase_ , decoder_input_ids=lowerCamelCase_ ) __a = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , lowerCamelCase_ ) def __UpperCAmelCase ( self ): __a = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) __a = shift_tokens_right(lowerCamelCase_ , 1 , 2 ) __a = np.equal(lowerCamelCase_ , 1 ).astype(np.floataa ).sum() __a = np.equal(lowerCamelCase_ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(lowerCamelCase_ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class __lowerCAmelCase ( _UpperCAmelCase , unittest.TestCase , _UpperCAmelCase ): '''simple docstring''' __UpperCAmelCase : Dict = True __UpperCAmelCase : Any = ( ( FlaxBlenderbotSmallModel, FlaxBlenderbotSmallForConditionalGeneration, ) if is_flax_available() else () ) __UpperCAmelCase : int = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else () def __UpperCAmelCase ( self ): __a = FlaxBlenderbotSmallModelTester(self ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __a = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) __a = model_class(lowerCamelCase_ ) @jax.jit def encode_jitted(_a , _a=None , **_a ): return model.encode(input_ids=lowerCamelCase_ , attention_mask=lowerCamelCase_ ) with self.subTest('''JIT Enabled''' ): __a = encode_jitted(**lowerCamelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __a = encode_jitted(**lowerCamelCase_ ).to_tuple() self.assertEqual(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) for jitted_output, output in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __a = model_class(lowerCamelCase_ ) __a = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) __a = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(_a , _a , _a ): return model.decode( decoder_input_ids=lowerCamelCase_ , decoder_attention_mask=lowerCamelCase_ , encoder_outputs=lowerCamelCase_ , ) with self.subTest('''JIT Enabled''' ): __a = decode_jitted(**lowerCamelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __a = decode_jitted(**lowerCamelCase_ ).to_tuple() self.assertEqual(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) for jitted_output, output in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __UpperCAmelCase ( self ): for model_class_name in self.all_model_classes: __a = model_class_name.from_pretrained('''facebook/blenderbot_small-90M''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids __a = np.ones((1, 1) ) * model.config.eos_token_id __a = model(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ )
718
"""simple docstring""" import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin lowercase_ = 1e-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=16 , _a=13 , _a=7 , _a=14 , _a=10 , _a=19 , _a=5 , _a=4 , _a=True , _a=16 , _a=2 , _a=4 , _a=4 , _a="gelu" , _a=0.1 , _a=0.1 , _a=[1, 2, 3, 4, 5] , _a=25 , _a=5 , ): __a = d_model __a = parent __a = batch_size __a = prediction_length __a = context_length __a = cardinality __a = num_time_features __a = lags_sequence __a = embedding_dimension __a = is_training __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = context_length __a = prediction_length + label_length __a = label_length __a = moving_average __a = autocorrelation_factor def __UpperCAmelCase ( self ): return AutoformerConfig( d_model=self.d_model , 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 , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def __UpperCAmelCase ( self , _a ): __a = config.context_length + max(config.lags_sequence ) __a = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) __a = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) __a = floats_tensor([self.batch_size, _past_length] ) __a = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs __a = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) __a = floats_tensor([self.batch_size, config.prediction_length] ) __a = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def __UpperCAmelCase ( self ): __a = self.get_config() __a = self.prepare_autoformer_inputs_dict(_a ) return config, inputs_dict def __UpperCAmelCase ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def __UpperCAmelCase ( self , _a , _a ): __a = AutoformerModel(config=_a ).to(_a ).eval() __a = model(**_a ) __a = outputs.encoder_last_hidden_state __a = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: __a = model.get_encoder() encoder.save_pretrained(_a ) __a = AutoformerEncoder.from_pretrained(_a ).to(_a ) __a , __a , __a , __a , __a = model.create_network_inputs(**_a ) __a , __a = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) __a = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) __a = encoder(inputs_embeds=_a )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) __a = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) __a = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) __a = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) __a = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: __a = model.get_decoder() decoder.save_pretrained(_a ) __a = AutoformerDecoder.from_pretrained(_a ).to(_a ) __a = decoder( trend=_a , inputs_embeds=_a , encoder_hidden_states=_a , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Any = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () __UpperCAmelCase : int = (AutoformerForPrediction,) if is_torch_available() else () __UpperCAmelCase : Any = {'feature-extraction': AutoformerModel} if is_torch_available() else {} __UpperCAmelCase : int = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : int = False __UpperCAmelCase : Any = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : int = False def __UpperCAmelCase ( self ): __a = AutoformerModelTester(self ) __a = ConfigTester(self , config_class=_a , has_text_modality=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: __a = model_class(_a ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_a ) __a , __a = model_class.from_pretrained(_a , output_loading_info=_a ) self.assertEqual(info['''missing_keys'''] , [] ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*_a ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = inspect.signature(getattr(_a , '''forward''' ) ) # The main input is the name of the argument after `self` __a = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''' ) expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ] ) self.assertListEqual(arg_names[: len(_a )] , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True __a = getattr(self.model_tester , '''seq_length''' , _a ) __a = getattr(self.model_tester , '''decoder_seq_length''' , _a ) __a = getattr(self.model_tester , '''encoder_seq_length''' , _a ) __a = getattr(self.model_tester , '''d_model''' , _a ) __a = getattr(self.model_tester , '''num_attention_heads''' , _a ) __a = d_model // num_attention_heads for model_class in self.all_model_classes: __a = True __a = False __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.encoder_attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) __a = len(_a ) __a = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(_a , _a ) # decoder attentions __a = outputs.decoder_attentions self.assertIsInstance(_a , (list, tuple) ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions __a = outputs.cross_attentions self.assertIsInstance(_a , (list, tuple) ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine __a = True __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + 2 , len(_a ) ) __a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def __UpperCAmelCase ( self ): super().test_retain_grad_hidden_states_attentions() def lowercase ( lowerCAmelCase__ : Optional[int]="train-batch.pt" ) -> List[str]: __a = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=lowerCAmelCase__ , repo_type='''dataset''' ) __a = torch.load(lowerCAmelCase__ , map_location=lowerCAmelCase__ ) return batch @require_torch @slow class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch() with torch.no_grad(): __a = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] __a = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=_a ) self.assertTrue(torch.allclose(output[0, :3, :3] , _a , atol=_a ) ) def __UpperCAmelCase ( self ): __a = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): __a = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state __a = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=_a ) self.assertTrue(torch.allclose(output[0, :3, :3] , _a , atol=_a ) ) def __UpperCAmelCase ( self ): __a = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): __a = model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) __a = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , _a ) __a = torch.tensor([3130.6763, 4056.5293, 7053.0786] , device=_a ) __a = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , _a , rtol=1E-1 ) )
65
0
"""simple docstring""" from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class __lowerCAmelCase : '''simple docstring''' pass
719
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str] ) -> Any: if isinstance(lowerCAmelCase__ , torch.Tensor ): return image elif isinstance(lowerCAmelCase__ , PIL.Image.Image ): __a = [image] if isinstance(image[0] , PIL.Image.Image ): __a = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] __a = np.concatenate(lowerCAmelCase__ , axis=0 ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 2_55.0 __a = image.transpose(0 , 3 , 1 , 2 ) __a = 2.0 * image - 1.0 __a = torch.from_numpy(lowerCAmelCase__ ) elif isinstance(image[0] , torch.Tensor ): __a = torch.cat(lowerCAmelCase__ , dim=0 ) return image def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[int]=0.99_95 ) -> int: if not isinstance(lowerCAmelCase__ , np.ndarray ): __a = True __a = va.device __a = va.cpu().numpy() __a = va.cpu().numpy() __a = np.sum(va * va / (np.linalg.norm(lowerCAmelCase__ ) * np.linalg.norm(lowerCAmelCase__ )) ) if np.abs(lowerCAmelCase__ ) > DOT_THRESHOLD: __a = (1 - t) * va + t * va else: __a = np.arccos(lowerCAmelCase__ ) __a = np.sin(lowerCAmelCase__ ) __a = theta_a * t __a = np.sin(lowerCAmelCase__ ) __a = np.sin(theta_a - theta_t ) / sin_theta_a __a = sin_theta_t / sin_theta_a __a = sa * va + sa * va if inputs_are_torch: __a = torch.from_numpy(lowerCAmelCase__ ).to(lowerCAmelCase__ ) return va def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[Any] ) -> int: __a = F.normalize(lowerCAmelCase__ , dim=-1 ) __a = F.normalize(lowerCAmelCase__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ) -> List[str]: for param in model.parameters(): __a = value class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a=None , _a=None , _a=None , ): super().__init__() self.register_modules( vae=_a , text_encoder=_a , clip_model=_a , tokenizer=_a , unet=_a , scheduler=_a , feature_extractor=_a , coca_model=_a , coca_tokenizer=_a , coca_transform=_a , ) __a = ( feature_extractor.size if isinstance(feature_extractor.size , _a ) else feature_extractor.size['''shortest_edge'''] ) __a = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , _a ) set_requires_grad(self.clip_model , _a ) def __UpperCAmelCase ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def __UpperCAmelCase ( self ): self.enable_attention_slicing(_a ) def __UpperCAmelCase ( self ): set_requires_grad(self.vae , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.vae , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.unet , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.unet , _a ) def __UpperCAmelCase ( self , _a , _a , _a ): # get the original timestep using init_timestep __a = min(int(num_inference_steps * strength ) , _a ) __a = max(num_inference_steps - init_timestep , 0 ) __a = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a=None ): if not isinstance(_a , torch.Tensor ): raise ValueError(f'''`image` has to be of type `torch.Tensor` but is {type(_a )}''' ) __a = image.to(device=_a , dtype=_a ) if isinstance(_a , _a ): __a = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_a ) ] __a = torch.cat(_a , dim=0 ) else: __a = self.vae.encode(_a ).latent_dist.sample(_a ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 0.1_8215 * init_latents __a = init_latents.repeat_interleave(_a , dim=0 ) __a = randn_tensor(init_latents.shape , generator=_a , device=_a , dtype=_a ) # get latents __a = self.scheduler.add_noise(_a , _a , _a ) __a = init_latents return latents def __UpperCAmelCase ( self , _a ): __a = self.coca_transform(_a ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): __a = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) __a = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def __UpperCAmelCase ( self , _a , _a ): __a = self.feature_extractor.preprocess(_a ) __a = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() __a = self.clip_model.get_image_features(_a ) __a = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_a ) __a = image_embeddings_clip.repeat_interleave(_a , dim=0 ) return image_embeddings_clip @torch.enable_grad() def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): __a = latents.detach().requires_grad_() __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a , encoder_hidden_states=_a ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): __a = self.scheduler.alphas_cumprod[timestep] __a = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __a = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 __a = torch.sqrt(_a ) __a = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , _a ): __a = self.scheduler.sigmas[index] __a = latents - sigma * noise_pred else: raise ValueError(f'''scheduler type {type(self.scheduler )} not supported''' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 1 / 0.1_8215 * sample __a = self.vae.decode(_a ).sample __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = transforms.Resize(self.feature_extractor_size )(_a ) __a = self.normalize(_a ).to(latents.dtype ) __a = self.clip_model.get_image_features(_a ) __a = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_a ) __a = spherical_dist_loss(_a , _a ).mean() * clip_guidance_scale __a = -torch.autograd.grad(_a , _a )[0] if isinstance(self.scheduler , _a ): __a = latents.detach() + grads * (sigma**2) __a = noise_pred_original else: __a = noise_pred_original - torch.sqrt(_a ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , _a , _a , _a = None , _a = None , _a = 512 , _a = 512 , _a = 0.6 , _a = 50 , _a = 7.5 , _a = 1 , _a = 0.0 , _a = 100 , _a = None , _a = "pil" , _a = True , _a = 0.8 , _a = 0.1 , _a = 0.1 , ): if isinstance(_a , _a ) and len(_a ) != batch_size: raise ValueError(f'''You have passed {batch_size} batch_size, but only {len(_a )} generators.''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if isinstance(_a , torch.Generator ) and batch_size > 1: __a = [generator] + [None] * (batch_size - 1) __a = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] __a = [x[0] for x in coca_is_none if x[1]] __a = ''', '''.join(_a ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(_a ): raise ValueError( f'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' f'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) __a = self.get_image_description(_a ) if style_prompt is None: if len(_a ): raise ValueError( f'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' f''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) __a = self.get_image_description(_a ) # get prompt text embeddings for content and style __a = self.tokenizer( _a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=_a , return_tensors='''pt''' , ) __a = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] __a = self.tokenizer( _a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=_a , return_tensors='''pt''' , ) __a = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] __a = slerp(_a , _a , _a ) # duplicate text embeddings for each generation per prompt __a = text_embeddings.repeat_interleave(_a , dim=0 ) # set timesteps __a = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) __a = {} if accepts_offset: __a = 1 self.scheduler.set_timesteps(_a , **_a ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) __a , __a = self.get_timesteps(_a , _a , self.device ) __a = timesteps[:1].repeat(_a ) # Preprocess image __a = preprocess(_a , _a , _a ) __a = self.prepare_latents( _a , _a , _a , text_embeddings.dtype , self.device , _a ) __a = preprocess(_a , _a , _a ) __a = self.prepare_latents( _a , _a , _a , text_embeddings.dtype , self.device , _a ) __a = slerp(_a , _a , _a ) if clip_guidance_scale > 0: __a = self.get_clip_image_embeddings(_a , _a ) __a = self.get_clip_image_embeddings(_a , _a ) __a = slerp( _a , _a , _a ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __a = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __a = content_text_input.input_ids.shape[-1] __a = self.tokenizer([''''''] , padding='''max_length''' , max_length=_a , return_tensors='''pt''' ) __a = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt __a = uncond_embeddings.repeat_interleave(_a , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __a = 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`. __a = (batch_size, self.unet.config.in_channels, height // 8, width // 8) __a = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps __a = torch.randn(_a , generator=_a , device='''cpu''' , dtype=_a ).to( self.device ) else: __a = torch.randn(_a , generator=_a , device=self.device , dtype=_a ) else: if latents.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) __a = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __a = 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] __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta # check if the scheduler accepts generator __a = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: __a = generator with self.progress_bar(total=_a ): for i, t in enumerate(_a ): # expand the latents if we are doing classifier free guidance __a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a , encoder_hidden_states=_a ).sample # perform classifier free guidance if do_classifier_free_guidance: __a , __a = noise_pred.chunk(2 ) __a = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: __a = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) __a , __a = self.cond_fn( _a , _a , _a , _a , _a , _a , _a , ) # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 1 / 0.1_8215 * latents __a = self.vae.decode(_a ).sample __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=_a , nsfw_content_detected=_a )
65
0
"""simple docstring""" from math import factorial def lowercase ( lowerCAmelCase__ : Optional[Any] = 20 ) -> int: __a = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... __a = n // 2 return int(factorial(lowerCAmelCase__ ) / (factorial(lowerCAmelCase__ ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(2_0)) else: try: lowercase_ = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number.")
720
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowercase_ = abspath(join(dirname(dirname(dirname(__file__))), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def lowercase ( lowerCAmelCase__ : List[Any] ) -> str: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int ) -> Union[str, Any]: from transformers.testing_utils import pytest_terminal_summary_main __a = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(lowerCAmelCase__ , id=lowerCAmelCase__ )
65
0
"""simple docstring""" import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowerCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = MgpstrTokenizer __UpperCAmelCase : Tuple = False __UpperCAmelCase : str = {} __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): super().setUp() # fmt: off __a = ["""[GO]""", """[s]""", """0""", """1""", """2""", """3""", """4""", """5""", """6""", """7""", """8""", """9""", """a""", """b""", """c""", """d""", """e""", """f""", """g""", """h""", """i""", """j""", """k""", """l""", """m""", """n""", """o""", """p""", """q""", """r""", """s""", """t""", """u""", """v""", """w""", """x""", """y""", """z"""] # fmt: on __a = dict(zip(_lowercase , range(len(_lowercase ) ) ) ) __a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(_lowercase ) + '''\n''' ) def __UpperCAmelCase ( self , **_a ): return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_lowercase ) def __UpperCAmelCase ( self , _a ): __a = """tester""" __a = """tester""" return input_text, output_text @unittest.skip('''MGP-STR always lower cases letters.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = self.get_tokenizers(do_lower_case=_lowercase ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __a = """[SPECIAL_TOKEN]""" tokenizer.add_special_tokens({'''cls_token''': special_token} ) __a = tokenizer.encode([special_token] , add_special_tokens=_lowercase ) self.assertEqual(len(_lowercase ) , 1 ) __a = tokenizer.decode(_lowercase , skip_special_tokens=_lowercase ) self.assertTrue(special_token not in decoded ) def __UpperCAmelCase ( self ): __a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __a = self.get_input_output_texts(_lowercase ) __a = tokenizer.tokenize(_lowercase ) __a = tokenizer.convert_tokens_to_ids(_lowercase ) __a = tokenizer.encode(_lowercase , add_special_tokens=_lowercase ) self.assertListEqual(_lowercase , _lowercase ) __a = tokenizer.convert_ids_to_tokens(_lowercase ) self.assertNotEqual(len(_lowercase ) , 0 ) __a = tokenizer.decode(_lowercase ) self.assertIsInstance(_lowercase , _lowercase ) self.assertEqual(text_a.replace(''' ''' , '''''' ) , _lowercase ) @unittest.skip('''MGP-STR tokenizer only handles one sequence.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''' ) def __UpperCAmelCase ( self ): pass
721
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase_ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __UpperCAmelCase : Any = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __UpperCAmelCase : Any = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __UpperCAmelCase : Dict = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def __UpperCAmelCase ( self , _a , _a , _a ): __a = ZeroShotClassificationPipeline( model=_a , tokenizer=_a , candidate_labels=['''polics''', '''health'''] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def __UpperCAmelCase ( self , _a , _a ): __a = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics''' ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) # No kwarg __a = classifier('''Who are you voting for in 2020?''' , ['''politics'''] ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics'''] ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics, public health''' ) self.assertEqual( _a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health'''] ) self.assertEqual( _a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) __a = classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''This text is about {}''' ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) # https://github.com/huggingface/transformers/issues/13846 __a = classifier(['''I am happy'''] , ['''positive''', '''negative'''] ) self.assertEqual( _a , [ {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} for i in range(1 ) ] , ) __a = classifier(['''I am happy''', '''I am sad'''] , ['''positive''', '''negative'''] ) self.assertEqual( _a , [ {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} for i in range(2 ) ] , ) with self.assertRaises(_a ): classifier('''''' , candidate_labels='''politics''' ) with self.assertRaises(_a ): classifier(_a , candidate_labels='''politics''' ) with self.assertRaises(_a ): classifier('''Who are you voting for in 2020?''' , candidate_labels='''''' ) with self.assertRaises(_a ): classifier('''Who are you voting for in 2020?''' , candidate_labels=_a ) with self.assertRaises(_a ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''Not formatting template''' , ) with self.assertRaises(_a ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template=_a , ) self.run_entailment_id(_a ) def __UpperCAmelCase ( self , _a ): __a = zero_shot_classifier.model.config __a = config.labelaid __a = zero_shot_classifier.entailment_id __a = {'''LABEL_0''': 0, '''LABEL_1''': 1, '''LABEL_2''': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) __a = {'''entailment''': 0, '''neutral''': 1, '''contradiction''': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __a = {'''ENTAIL''': 0, '''NON-ENTAIL''': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __a = {'''ENTAIL''': 2, '''NEUTRAL''': 1, '''CONTR''': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) __a = original_labelaid self.assertEqual(_a , zero_shot_classifier.entailment_id ) @require_torch def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( '''Who are you voting for in 2020?''' * 100 , candidate_labels=['''politics''', '''public health''', '''science'''] ) @require_torch def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @require_tf def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''tf''' , ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @slow @require_torch def __UpperCAmelCase ( self ): __a = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''pt''' ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) __a = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=_a , ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , ) @slow @require_tf def __UpperCAmelCase ( self ): __a = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''tf''' ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) __a = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=_a , ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , )
65
0
"""simple docstring""" from typing import Dict, List, Optional, Tuple, 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_torch_available, is_torch_tensor, logging if is_torch_available(): import torch lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _lowercase ): '''simple docstring''' __UpperCAmelCase : Dict = ['''pixel_values'''] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BILINEAR , _a = True , _a = None , _a = True , _a = 1 / 255 , _a = True , _a = None , _a = None , **_a , ): super().__init__(**A_ ) __a = size if size is not None else {'''shortest_edge''': 256} __a = get_size_dict(A_ , default_to_square=A_ ) __a = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} __a = get_size_dict(A_ , param_name='''crop_size''' ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __a = image_std if image_std is not None else IMAGENET_STANDARD_STD def __UpperCAmelCase ( self , _a , _a , _a = PILImageResampling.BICUBIC , _a = None , **_a , ): __a = get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) __a = get_resize_output_image_size(A_ , size=size['''shortest_edge'''] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def __UpperCAmelCase ( self , _a , _a , _a = None , **_a , ): __a = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}''' ) return center_crop(A_ , size=(size['''height'''], size['''width''']) , data_format=A_ , **A_ ) def __UpperCAmelCase ( self , _a , _a , _a = None , **_a ): return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def __UpperCAmelCase ( self , _a , _a , _a , _a = None , **_a , ): return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def __UpperCAmelCase ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ): __a = do_resize if do_resize is not None else self.do_resize __a = size if size is not None else self.size __a = get_size_dict(A_ , default_to_square=A_ ) __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(A_ , param_name='''crop_size''' ) __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) 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. __a = [to_numpy_array(A_ ) for image in images] if do_resize: __a = [self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __a = [self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __a = [self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __a = [self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __a = [to_channel_dimension_format(A_ , A_ ) for image in images] __a = {'''pixel_values''': images} return BatchFeature(data=A_ , tensor_type=A_ ) def __UpperCAmelCase ( self , _a , _a = None ): __a = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A_ ) != len(A_ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(A_ ): __a = target_sizes.numpy() __a = [] for idx in range(len(A_ ) ): __a = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=A_ ) __a = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A_ ) else: __a = logits.argmax(dim=1 ) __a = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
700
"""simple docstring""" import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowercase ( lowerCAmelCase__ : Optional[int] ) -> int: monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pytest.fixture def lowercase ( lowerCAmelCase__ : Any ) -> Any: class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): __a = metric_id class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Any = [MetricMock(__SCREAMING_SNAKE_CASE ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']] def __UpperCAmelCase ( self ): return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() ) @pytest.mark.parametrize( '''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple ) -> Optional[int]: if "tmp_path" in args: __a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(lowerCAmelCase__ , match='''https://huggingface.co/docs/evaluate''' ): func(*lowerCAmelCase__ )
65
0
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class __lowerCAmelCase ( lowercase__ ): '''simple docstring''' __UpperCAmelCase : jnp.ndarray __UpperCAmelCase : jnp.ndarray class __lowerCAmelCase ( nn.Module ): '''simple docstring''' __UpperCAmelCase : int __UpperCAmelCase : Tuple[int] = (1_6, 3_2, 9_6, 2_5_6) __UpperCAmelCase : jnp.dtype = jnp.floataa def __UpperCAmelCase ( self ): __a = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) __a = [] for i in range(len(self.block_out_channels ) - 1 ): __a = self.block_out_channels[i] __a = self.block_out_channels[i + 1] __a = nn.Conv( _a , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(_a ) __a = nn.Conv( _a , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(_a ) __a = blocks __a = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , _a ): __a = self.conv_in(_a ) __a = nn.silu(_a ) for block in self.blocks: __a = block(_a ) __a = nn.silu(_a ) __a = self.conv_out(_a ) return embedding @flax_register_to_config class __lowerCAmelCase ( nn.Module , lowercase__ , lowercase__ ): '''simple docstring''' __UpperCAmelCase : int = 3_2 __UpperCAmelCase : int = 4 __UpperCAmelCase : Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) __UpperCAmelCase : Union[bool, Tuple[bool]] = False __UpperCAmelCase : Tuple[int] = (3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0) __UpperCAmelCase : int = 2 __UpperCAmelCase : Union[int, Tuple[int]] = 8 __UpperCAmelCase : Optional[Union[int, Tuple[int]]] = None __UpperCAmelCase : int = 1_2_8_0 __UpperCAmelCase : float = 0.0 __UpperCAmelCase : bool = False __UpperCAmelCase : jnp.dtype = jnp.floataa __UpperCAmelCase : bool = True __UpperCAmelCase : int = 0 __UpperCAmelCase : str = "rgb" __UpperCAmelCase : Tuple[int] = (1_6, 3_2, 9_6, 2_5_6) def __UpperCAmelCase ( self , _a ): # init input tensors __a = (1, self.in_channels, self.sample_size, self.sample_size) __a = jnp.zeros(_a , dtype=jnp.floataa ) __a = jnp.ones((1,) , dtype=jnp.intaa ) __a = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) __a = (1, 3, self.sample_size * 8, self.sample_size * 8) __a = jnp.zeros(_a , dtype=jnp.floataa ) __a , __a = jax.random.split(_a ) __a = {'''params''': params_rng, '''dropout''': dropout_rng} return self.init(_a , _a , _a , _a , _a )["params"] def __UpperCAmelCase ( self ): __a = self.block_out_channels __a = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. __a = self.num_attention_heads or self.attention_head_dim # input __a = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time __a = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) __a = FlaxTimestepEmbedding(_a , dtype=self.dtype ) __a = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) __a = self.only_cross_attention if isinstance(_a , _a ): __a = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_a , _a ): __a = (num_attention_heads,) * len(self.down_block_types ) # down __a = [] __a = [] __a = block_out_channels[0] __a = nn.Conv( _a , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_a ) for i, down_block_type in enumerate(self.down_block_types ): __a = output_channel __a = block_out_channels[i] __a = i == len(_a ) - 1 if down_block_type == "CrossAttnDownBlock2D": __a = FlaxCrossAttnDownBlockaD( in_channels=_a , out_channels=_a , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: __a = FlaxDownBlockaD( in_channels=_a , out_channels=_a , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_a ) for _ in range(self.layers_per_block ): __a = nn.Conv( _a , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_a ) if not is_final_block: __a = nn.Conv( _a , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_a ) __a = down_blocks __a = controlnet_down_blocks # mid __a = block_out_channels[-1] __a = FlaxUNetMidBlockaDCrossAttn( in_channels=_a , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) __a = nn.Conv( _a , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , _a , _a , _a , _a , _a = 1.0 , _a = True , _a = False , ): __a = self.controlnet_conditioning_channel_order if channel_order == "bgr": __a = jnp.flip(_a , axis=1 ) # 1. time if not isinstance(_a , jnp.ndarray ): __a = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_a , jnp.ndarray ) and len(timesteps.shape ) == 0: __a = timesteps.astype(dtype=jnp.floataa ) __a = jnp.expand_dims(_a , 0 ) __a = self.time_proj(_a ) __a = self.time_embedding(_a ) # 2. pre-process __a = jnp.transpose(_a , (0, 2, 3, 1) ) __a = self.conv_in(_a ) __a = jnp.transpose(_a , (0, 2, 3, 1) ) __a = self.controlnet_cond_embedding(_a ) sample += controlnet_cond # 3. down __a = (sample,) for down_block in self.down_blocks: if isinstance(_a , _a ): __a , __a = down_block(_a , _a , _a , deterministic=not train ) else: __a , __a = down_block(_a , _a , deterministic=not train ) down_block_res_samples += res_samples # 4. mid __a = self.mid_block(_a , _a , _a , deterministic=not train ) # 5. contronet blocks __a = () for down_block_res_sample, controlnet_block in zip(_a , self.controlnet_down_blocks ): __a = controlnet_block(_a ) controlnet_down_block_res_samples += (down_block_res_sample,) __a = controlnet_down_block_res_samples __a = self.controlnet_mid_block(_a ) # 6. scaling __a = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=_a , mid_block_res_sample=_a )
701
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> int: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or number < 0: raise ValueError('''Input must be a non-negative integer''' ) __a = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput lowercase_ : Any = logging.get_logger(__name__) # pylint: disable=invalid-name def lowercase ( lowerCAmelCase__ : Union[List, PIL.Image.Image, torch.Tensor] ) -> int: warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''' , lowerCAmelCase__ , ) if isinstance(lowerCAmelCase__ , torch.Tensor ): return image elif isinstance(lowerCAmelCase__ , PIL.Image.Image ): __a = [image] if isinstance(image[0] , PIL.Image.Image ): __a , __a = image[0].size __a , __a = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 __a = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] __a = np.concatenate(lowerCAmelCase__ , axis=0 ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 2_55.0 __a = image.transpose(0 , 3 , 1 , 2 ) __a = 2.0 * image - 1.0 __a = torch.from_numpy(lowerCAmelCase__ ) elif isinstance(image[0] , torch.Tensor ): __a = torch.cat(lowerCAmelCase__ , dim=0 ) return image def lowercase ( lowerCAmelCase__ : Union[List, PIL.Image.Image, torch.Tensor] ) -> List[str]: if isinstance(lowerCAmelCase__ , torch.Tensor ): return mask elif isinstance(lowerCAmelCase__ , PIL.Image.Image ): __a = [mask] if isinstance(mask[0] , PIL.Image.Image ): __a , __a = mask[0].size __a , __a = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __a = [np.array(m.convert('''L''' ).resize((w, h) , resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] __a = np.concatenate(lowerCAmelCase__ , axis=0 ) __a = mask.astype(np.floataa ) / 2_55.0 __a = 0 __a = 1 __a = torch.from_numpy(lowerCAmelCase__ ) elif isinstance(mask[0] , torch.Tensor ): __a = torch.cat(lowerCAmelCase__ , dim=0 ) return mask class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = 4_2 __UpperCAmelCase : str = 4_2 def __init__( self , _a , _a ): super().__init__() self.register_modules(unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _a , _a , _a = 250 , _a = 0.0 , _a = 10 , _a = 10 , _a = None , _a = "pil" , _a = True , ): __a = image __a = _preprocess_image(_a ) __a = original_image.to(device=self.device , dtype=self.unet.dtype ) __a = _preprocess_mask(_a ) __a = mask_image.to(device=self.device , dtype=self.unet.dtype ) __a = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(_a , _a ) and len(_a ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_a )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) __a = original_image.shape __a = randn_tensor(_a , generator=_a , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(_a , _a , _a , self.device ) __a = eta __a = self.scheduler.timesteps[0] + 1 __a = generator[0] if isinstance(_a , _a ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual __a = self.unet(_a , _a ).sample # compute previous image: x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , _a , _a , _a ).prev_sample else: # compute the reverse: x_t-1 -> x_t __a = self.scheduler.undo_step(_a , _a , _a ) __a = t __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
702
"""simple docstring""" import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[Any] ) -> str: assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int ) -> Tuple: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( '''features''' , [ None, {'''text''': '''string'''}, {'''text''': '''int32'''}, {'''text''': '''float32'''}, ] , ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Union[str, Any] ) -> Optional[int]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) __a = TextDatasetReader(lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict ) -> Optional[Any]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , split=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any] ) -> Dict: if issubclass(lowerCAmelCase__ , lowerCAmelCase__ ): __a = text_path elif issubclass(lowerCAmelCase__ , lowerCAmelCase__ ): __a = [text_path] __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Union[str, Any]=("train",) ) -> Optional[Any]: assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) for split in splits: __a = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any] ) -> Union[str, Any]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a = TextDatasetReader({'''train''': text_path} , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( '''features''' , [ None, {'''text''': '''string'''}, {'''text''': '''int32'''}, {'''text''': '''float32'''}, ] , ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] ) -> str: __a = tmp_path / '''cache''' # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" __a = {'''text''': '''string'''} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) __a = TextDatasetReader({'''train''': text_path} , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple ) -> Dict: if split: __a = {split: text_path} else: __a = '''train''' __a = {'''train''': text_path, '''test''': text_path} __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() )
65
0
# Note: if you intend to run this script make sure you look under scripts/fsmt/ # to locate the appropriate script to do the work correctly. There is a set of scripts to: # - download and prepare data and run the conversion script # - perform eval to get the best hparam into the config # - generate model_cards - useful if you have multiple models from the same paper import argparse import json import os import re from collections import OrderedDict from os.path import basename, dirname import fairseq import torch from fairseq import hub_utils from fairseq.data.dictionary import Dictionary from transformers import FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() lowercase_ = 2 # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping` # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults: # # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users) # * `early_stopping`: `False` consistently scored better # * `length_penalty` varied, so will assign the best one depending on the model lowercase_ = { # fairseq: """wmt19-ru-en""": {"""length_penalty""": 1.1}, """wmt19-en-ru""": {"""length_penalty""": 1.15}, """wmt19-en-de""": {"""length_penalty""": 1.0}, """wmt19-de-en""": {"""length_penalty""": 1.1}, # allenai: """wmt16-en-de-dist-12-1""": {"""length_penalty""": 0.6}, """wmt16-en-de-dist-6-1""": {"""length_penalty""": 0.6}, """wmt16-en-de-12-1""": {"""length_penalty""": 0.8}, """wmt19-de-en-6-6-base""": {"""length_penalty""": 0.6}, """wmt19-de-en-6-6-big""": {"""length_penalty""": 0.6}, } # this remaps the different models to their organization names lowercase_ = {} for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowercase_ = """facebook""" for m in [ "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big", ]: lowercase_ = """allenai""" def lowercase ( lowerCAmelCase__ : int ) -> Optional[int]: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} __a = dict((re.sub(r'''@@$''' , '''''' , snake_case_ ), v) if k.endswith('''@@''' ) else (re.sub(r'''$''' , '''</w>''' , snake_case_ ), v) for k, v in d.items() ) __a = "<s> <pad> </s> <unk>".split() # restore the special tokens for k in keep_keys: del da[f'''{k}</w>'''] __a = d[k] # restore return da def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Union[str, Any] ) -> str: # prep assert os.path.exists(snake_case_ ) os.makedirs(snake_case_ , exist_ok=snake_case_ ) print(f'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models __a = basename(snake_case_ ) __a = dirname(snake_case_ ) __a = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel __a = cls.hub_models() __a = {"bpe": "fastbpe", "tokenizer": "moses"} __a = "." # note: since the model dump is old, fairseq has upgraded its model some # time later, and it does a whole lot of rewrites and splits on the saved # weights, therefore we can't use torch.load() directly on the model file. # see: upgrade_state_dict(state_dict) in fairseq_model.py print(f'''using checkpoint {checkpoint_file}''' ) __a = hub_utils.from_pretrained( snake_case_ , snake_case_ , snake_case_ , archive_map=snake_case_ , **snake_case_ ) __a = vars(chkpt['''args''']['''model'''] ) __a = args["source_lang"] __a = args["target_lang"] __a = dirname(snake_case_ ) __a = basename(snake_case_ ) # dicts __a = os.path.join(snake_case_ , f'''dict.{src_lang}.txt''' ) __a = os.path.join(snake_case_ , f'''dict.{tgt_lang}.txt''' ) __a = Dictionary.load(snake_case_ ) __a = rewrite_dict_keys(src_dict.indices ) __a = len(snake_case_ ) __a = os.path.join(snake_case_ , '''vocab-src.json''' ) print(f'''Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records''' ) with open(snake_case_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(snake_case_ , ensure_ascii=snake_case_ , indent=snake_case_ ) ) # detect whether this is a do_lower_case situation, which can be derived by checking whether we # have at least one uppercase letter in the source vocab __a = True for k in src_vocab.keys(): if not k.islower(): __a = False break __a = Dictionary.load(snake_case_ ) __a = rewrite_dict_keys(tgt_dict.indices ) __a = len(snake_case_ ) __a = os.path.join(snake_case_ , '''vocab-tgt.json''' ) print(f'''Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records''' ) with open(snake_case_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(snake_case_ , ensure_ascii=snake_case_ , indent=snake_case_ ) ) # merges_file (bpecodes) __a = os.path.join(snake_case_ , VOCAB_FILES_NAMES['''merges_file'''] ) for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code" __a = os.path.join(snake_case_ , snake_case_ ) if os.path.exists(snake_case_ ): break with open(snake_case_ , encoding='''utf-8''' ) as fin: __a = fin.read() __a = re.sub(r''' \d+$''' , '''''' , snake_case_ , 0 , re.M ) # remove frequency number print(f'''Generating {merges_file}''' ) with open(snake_case_ , '''w''' , encoding='''utf-8''' ) as fout: fout.write(snake_case_ ) # model config __a = os.path.join(snake_case_ , '''config.json''' ) # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe - # may have to modify the tokenizer if a different type is used by a future model assert args["bpe"] == "fastbpe", f'''need to extend tokenizer to support bpe={args['bpe']}''' assert args["tokenizer"] == "moses", f'''need to extend tokenizer to support bpe={args['tokenizer']}''' __a = { "architectures": ["FSMTForConditionalGeneration"], "model_type": "fsmt", "activation_dropout": args["activation_dropout"], "activation_function": "relu", "attention_dropout": args["attention_dropout"], "d_model": args["decoder_embed_dim"], "dropout": args["dropout"], "init_std": 0.02, "max_position_embeddings": args["max_source_positions"], "num_hidden_layers": args["encoder_layers"], "src_vocab_size": src_vocab_size, "tgt_vocab_size": tgt_vocab_size, "langs": [src_lang, tgt_lang], "encoder_attention_heads": args["encoder_attention_heads"], "encoder_ffn_dim": args["encoder_ffn_embed_dim"], "encoder_layerdrop": args["encoder_layerdrop"], "encoder_layers": args["encoder_layers"], "decoder_attention_heads": args["decoder_attention_heads"], "decoder_ffn_dim": args["decoder_ffn_embed_dim"], "decoder_layerdrop": args["decoder_layerdrop"], "decoder_layers": args["decoder_layers"], "bos_token_id": 0, "pad_token_id": 1, "eos_token_id": 2, "is_encoder_decoder": True, "scale_embedding": not args["no_scale_embedding"], "tie_word_embeddings": args["share_all_embeddings"], } # good hparam defaults to start with __a = 5 __a = False if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]: __a = best_score_hparams[model_dir]["length_penalty"] else: __a = 1.0 print(f'''Generating {fsmt_model_config_file}''' ) with open(snake_case_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(snake_case_ , ensure_ascii=snake_case_ , indent=snake_case_ ) ) # tokenizer config __a = os.path.join(snake_case_ , snake_case_ ) __a = { "langs": [src_lang, tgt_lang], "model_max_length": 1024, "do_lower_case": do_lower_case, } print(f'''Generating {fsmt_tokenizer_config_file}''' ) with open(snake_case_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(snake_case_ , ensure_ascii=snake_case_ , indent=snake_case_ ) ) # model __a = chkpt["models"][0] __a = model.state_dict() # rename keys to start with 'model.' __a = OrderedDict(('''model.''' + k, v) for k, v in model_state_dict.items() ) # remove unneeded keys __a = [ "model.model", "model.encoder.version", "model.decoder.version", "model.encoder_embed_tokens.weight", "model.decoder_embed_tokens.weight", "model.encoder.embed_positions._float_tensor", "model.decoder.embed_positions._float_tensor", ] for k in ignore_keys: model_state_dict.pop(snake_case_ , snake_case_ ) __a = FSMTConfig.from_pretrained(snake_case_ ) __a = FSMTForConditionalGeneration(snake_case_ ) # check that it loads ok model_new.load_state_dict(snake_case_ , strict=snake_case_ ) # save __a = os.path.join(snake_case_ , snake_case_ ) print(f'''Generating {pytorch_weights_dump_path}''' ) torch.save(snake_case_ , snake_case_ ) print('''Conversion is done!''' ) print('''\nLast step is to upload the files to s3''' ) print(f'''cd {data_root}''' ) print(f'''transformers-cli upload {model_dir}''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fsmt_checkpoint_path", default=None, type=str, required=True, help=( "Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts," " bpecodes, etc." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) lowercase_ = parser.parse_args() convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
703
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=4 , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_attention_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_choices def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_attention_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() __a = config_and_inputs __a = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class __lowerCAmelCase ( lowercase__ , unittest.TestCase ): '''simple docstring''' snake_case : Union[str, Any] = True snake_case : List[str] = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def __UpperCAmelCase ( self ): __a = FlaxRoFormerModelTester(self ) @slow def __UpperCAmelCase ( self ): for model_class_name in self.all_model_classes: __a = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''' , from_pt=_a ) __a = model(np.ones((1, 1) ) ) self.assertIsNotNone(_a ) @require_flax class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __a = jnp.array([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = 50_000 __a = (1, 6, vocab_size) self.assertEqual(output.shape , _a ) __a = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
704
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir("fixtures/test_sentencepiece_bpe_char.model") @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = SpeechTaTokenizer __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = True def __UpperCAmelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing __a = SpeechTaTokenizer(_a ) __a = AddedToken('''<mask>''' , lstrip=_a , rstrip=_a ) __a = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self , _a ): __a = '''this is a test''' __a = '''this is a test''' return input_text, output_text def __UpperCAmelCase ( self , _a , _a=False , _a=20 , _a=5 ): __a , __a = self.get_input_output_texts(_a ) __a = tokenizer.encode(_a , add_special_tokens=_a ) __a = tokenizer.decode(_a , clean_up_tokenization_spaces=_a ) return text, ids def __UpperCAmelCase ( self ): __a = '''<pad>''' __a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def __UpperCAmelCase ( self ): __a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(_a ) , 81 ) def __UpperCAmelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __UpperCAmelCase ( self ): __a = self.get_tokenizers(do_lower_case=_a ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) __a = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] __a = tokenizer.add_tokens(_a ) __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) self.assertEqual(_a , _a ) self.assertEqual(_a , len(_a ) ) self.assertEqual(_a , all_size + len(_a ) ) __a = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=_a ) self.assertGreaterEqual(len(_a ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) __a = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} __a = tokenizer.add_special_tokens(_a ) __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) self.assertEqual(_a , _a ) self.assertEqual(_a , len(_a ) ) self.assertEqual(_a , all_size_a + len(_a ) ) __a = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=_a ) self.assertGreaterEqual(len(_a ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = self.get_tokenizer() __a = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(_a , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) __a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) __a = tokenizer.convert_tokens_to_ids(_a ) # fmt: off self.assertListEqual(_a , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on __a = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def __UpperCAmelCase ( self ): # Use custom sequence because this tokenizer does not handle numbers. __a = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off __a = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=_a , )
65
0
"""simple docstring""" import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def lowercase ( lowerCAmelCase__ : Optional[int]=None ) -> Union[str, Any]: if subparsers is not None: __a = subparsers.add_parser('''env''' ) else: __a = argparse.ArgumentParser('''Accelerate env command''' ) parser.add_argument( '''--config_file''' , default=lowerCAmelCase__ , help='''The config file to use for the default values in the launching script.''' ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase__ ) return parser def lowercase ( lowerCAmelCase__ : int ) -> str: __a = torch.__version__ __a = torch.cuda.is_available() __a = is_xpu_available() __a = is_npu_available() __a = """Not found""" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase__ ): __a = load_config_from_file(args.config_file ).to_dict() __a = { """`Accelerate` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Numpy version""": np.__version__, """PyTorch version (GPU?)""": f'''{pt_version} ({pt_cuda_available})''', """PyTorch XPU available""": str(lowerCAmelCase__ ), """PyTorch NPU available""": str(lowerCAmelCase__ ), """System RAM""": f'''{psutil.virtual_memory().total / 1024 ** 3:.2f} GB''', } if pt_cuda_available: __a = torch.cuda.get_device_name() print('''\nCopy-and-paste the text below in your GitHub issue\n''' ) print('''\n'''.join([f'''- {prop}: {val}''' for prop, val in info.items()] ) ) print('''- `Accelerate` default config:''' if args.config_file is None else '''- `Accelerate` config passed:''' ) __a = ( """\n""".join([f'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else f'''\t{accelerate_config}''' ) print(lowerCAmelCase__ ) __a = accelerate_config return info def lowercase ( ) -> List[str]: __a = env_command_parser() __a = parser.parse_args() env_command(lowerCAmelCase__ ) return 0 if __name__ == "__main__": raise SystemExit(main())
705
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = ['input_features', 'attention_mask'] def __init__( self , _a=80 , _a=16_000 , _a=0.0 , _a=10 , _a=25 , _a="hamming_window" , _a=3_2768.0 , _a=0.97 , _a=1.0 , _a=True , _a=True , _a=False , **_a , ): super().__init__(feature_size=_a , sampling_rate=_a , padding_value=_a , **_a ) __a = feature_size __a = sampling_rate __a = padding_value __a = hop_length __a = win_length __a = frame_signal_scale __a = preemphasis_coeff __a = mel_floor __a = normalize_means __a = normalize_vars __a = win_function __a = return_attention_mask __a = win_length * sampling_rate // 1_000 __a = hop_length * sampling_rate // 1_000 __a = optimal_fft_length(self.sample_size ) __a = (self.n_fft // 2) + 1 def __UpperCAmelCase ( self , _a ): if self.win_function == "hamming_window": __a = window_function(window_length=self.sample_size , name=self.win_function , periodic=_a ) else: __a = window_function(window_length=self.sample_size , name=self.win_function ) __a = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) __a = spectrogram( one_waveform * self.frame_signal_scale , window=_a , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=_a , preemphasis=self.preemphasis_coeff , mel_filters=_a , mel_floor=self.mel_floor , log_mel='''log''' , ) return msfc_features.T def __UpperCAmelCase ( self , _a , _a , _a ): # make sure we normalize float32 arrays if self.normalize_means: __a = x[:input_length].mean(axis=0 ) __a = np.subtract(_a , _a ) if self.normalize_vars: __a = x[:input_length].std(axis=0 ) __a = np.divide(_a , _a ) if input_length < x.shape[0]: __a = padding_value # make sure array is in float32 __a = x.astype(np.floataa ) return x def __UpperCAmelCase ( self , _a , _a = None ): __a = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(_a , _a , self.padding_value ) for x, n in zip(_a , _a )] def __call__( self , _a , _a = False , _a = None , _a = False , _a = None , _a = None , _a = None , _a = None , **_a , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with''' f''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __a = isinstance(_a , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) __a = is_batched_numpy or ( isinstance(_a , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __a = [np.asarray(_a , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_a , np.ndarray ): __a = np.asarray(_a , dtype=np.floataa ) elif isinstance(_a , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __a = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __a = [raw_speech] # extract fbank features __a = [self._extract_mfsc_features(_a ) for one_waveform in raw_speech] # convert into correct format for padding __a = BatchFeature({'''input_features''': features} ) __a = self.pad( _a , padding=_a , max_length=_a , truncation=_a , pad_to_multiple_of=_a , return_attention_mask=_a , **_a , ) # make sure list is in array format __a = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , _a ): __a = [np.asarray(_a , dtype=np.floataa ) for feature in input_features] __a = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __a = [np.asarray(_a , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: __a = ( np.array(_a , dtype=np.intaa ) if self._get_padding_strategies(_a , max_length=_a ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) __a = self.normalize( padded_inputs['''input_features'''] , attention_mask=_a ) if return_tensors is not None: __a = padded_inputs.convert_to_tensors(_a ) return padded_inputs
65
0
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration lowercase_ = 5_0_0_0_0 lowercase_ = 5_0_0_0 lowercase_ , lowercase_ = os.path.split(__file__) lowercase_ = os.path.join(RESULTS_BASEPATH, "results", RESULTS_FILENAME.replace(".py", ".json")) @get_duration def lowercase ( lowerCAmelCase__ : datasets.Dataset , lowerCAmelCase__ : Dict ) -> int: for i in range(snake_case__ ): __a = dataset[i] @get_duration def lowercase ( lowerCAmelCase__ : datasets.Dataset , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : str ) -> Any: for i in range(0 , len(snake_case__ ) , snake_case__ ): __a = dataset[i : i + batch_size] @get_duration def lowercase ( lowerCAmelCase__ : datasets.Dataset , lowerCAmelCase__ : str , lowerCAmelCase__ : int ) -> Tuple: with dataset.formatted_as(type=snake_case__ ): for i in range(snake_case__ ): __a = dataset[i] @get_duration def lowercase ( lowerCAmelCase__ : datasets.Dataset , lowerCAmelCase__ : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : Union[str, Any] ) -> List[str]: with dataset.formatted_as(type=snake_case__ ): for i in range(0 , snake_case__ , snake_case__ ): __a = dataset[i : i + batch_size] def lowercase ( ) -> List[Any]: __a = {"""num examples""": SPEED_TEST_N_EXAMPLES} __a = [ (read, {"""length""": SMALL_TEST}), (read, {"""length""": SPEED_TEST_N_EXAMPLES}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 10}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 100}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1000}), (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """pandas""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """torch""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """tensorflow""", """length""": SMALL_TEST}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 10}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1000}), ] __a = [ (read, {"""length""": SMALL_TEST}), (read, {"""length""": SPEED_TEST_N_EXAMPLES}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 10}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 100}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1000}), (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 10}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1000}), ] with tempfile.TemporaryDirectory() as tmp_dir: print('''generating dataset''' ) __a = datasets.Features( {'''list''': datasets.Sequence(datasets.Value('''float32''' ) ), '''numbers''': datasets.Value('''float32''' )} ) __a = generate_example_dataset( os.path.join(snake_case__ , '''dataset.arrow''' ) , snake_case__ , num_examples=snake_case__ , seq_shapes={'''list''': (100,)} , ) print('''first set of iterations''' ) for func, kwargs in functions: print(func.__name__ , str(snake_case__ ) ) __a = func(snake_case__ , **snake_case__ ) print('''shuffling dataset''' ) __a = dataset.shuffle() print('''Second set of iterations (after shuffling''' ) for func, kwargs in functions_shuffled: print('''shuffled ''' , func.__name__ , str(snake_case__ ) ) __a = func( snake_case__ , **snake_case__ ) with open(snake_case__ , '''wb''' ) as f: f.write(json.dumps(snake_case__ ).encode('''utf-8''' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
706
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env' ) @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue_model_parallelism.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_6_0_0, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_6_0_0, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, ] ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=_a , ) assert hasattr(self , '''env''' ) def __UpperCAmelCase ( self , _a ): # configuration for running training on smdistributed Model Parallel __a = { '''enabled''': True, '''processes_per_host''': 8, } __a = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __a = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __a = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=_a , instance_type=self.instance_type , debugger_hook_config=_a , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 500, } , metric_definitions=self.env.metric_definitions , distribution=_a , py_version='''py36''' , ) def __UpperCAmelCase ( self , _a ): TrainingJobAnalytics(_a ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __UpperCAmelCase ( self , _a ): # create estimator __a = self.create_estimator(_a ) # run training estimator.fit() # result dataframe __a = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __a = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 999_999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , _a )
65
0
"""simple docstring""" import math from collections.abc import Iterator from itertools import takewhile def lowercase ( lowerCAmelCase__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__snake_case ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( ) -> Iterator[int]: __a = 2 while True: if is_prime(__snake_case ): yield num num += 1 def lowercase ( lowerCAmelCase__ : Optional[Any] = 2000000 ) -> int: return sum(takewhile(lambda lowerCAmelCase__ : x < n , prime_generator() ) ) if __name__ == "__main__": print(F'''{solution() = }''')
707
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
65
0
"""simple docstring""" import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' __a = XCLIPTextConfig() # derive patch size from model name __a = model_name.find('''patch''' ) __a = int(model_name[start_idx + len('''patch''' ) : start_idx + len('''patch''' ) + 2] ) __a = XCLIPVisionConfig(patch_size=UpperCAmelCase__ , num_frames=UpperCAmelCase__ ) if "large" in model_name: __a = 768 __a = 3072 __a = 12 __a = 1024 __a = 4096 __a = 16 __a = 24 __a = 768 __a = 3072 if model_name == "xclip-large-patch14-16-frames": __a = 336 __a = XCLIPConfig.from_text_vision_configs(UpperCAmelCase__ , UpperCAmelCase__ ) if "large" in model_name: __a = 768 return config def lowercase ( lowerCAmelCase__ : Optional[int] ) -> Optional[int]: '''simple docstring''' if name == "token_embedding.weight": __a = name.replace('''token_embedding.weight''' , '''text_model.embeddings.token_embedding.weight''' ) if name == "positional_embedding": __a = name.replace('''positional_embedding''' , '''text_model.embeddings.position_embedding.weight''' ) if "ln_1" in name: __a = name.replace('''ln_1''' , '''layer_norm1''' ) if "ln_2" in name: __a = name.replace('''ln_2''' , '''layer_norm2''' ) if "c_fc" in name: __a = name.replace('''c_fc''' , '''fc1''' ) if "c_proj" in name: __a = name.replace('''c_proj''' , '''fc2''' ) if name.startswith('''transformer.resblocks''' ): __a = name.replace('''transformer.resblocks''' , '''text_model.encoder.layers''' ) if "attn.out_proj" in name and "message" not in name: __a = name.replace('''attn.out_proj''' , '''self_attn.out_proj''' ) if "ln_final" in name: __a = name.replace('''ln_final''' , '''text_model.final_layer_norm''' ) # visual encoder if name == "visual.class_embedding": __a = name.replace('''visual.class_embedding''' , '''vision_model.embeddings.class_embedding''' ) if name == "visual.positional_embedding": __a = name.replace('''visual.positional_embedding''' , '''vision_model.embeddings.position_embedding.weight''' ) if name.startswith('''visual.transformer.resblocks''' ): __a = name.replace('''visual.transformer.resblocks''' , '''vision_model.encoder.layers''' ) if "visual.conv1" in name: __a = name.replace('''visual.conv1''' , '''vision_model.embeddings.patch_embedding''' ) if "visual.ln_pre" in name: __a = name.replace('''visual.ln_pre''' , '''vision_model.pre_layernorm''' ) if "visual.ln_post" in name: __a = name.replace('''visual.ln_post''' , '''vision_model.post_layernorm''' ) if "visual.proj" in name: __a = name.replace('''visual.proj''' , '''visual_projection.weight''' ) if "text_projection" in name: __a = name.replace('''text_projection''' , '''text_projection.weight''' ) # things on top if "prompts_visual_proj" in name: __a = name.replace('''prompts_visual_proj''' , '''prompts_visual_projection''' ) if "prompts_visual_ln" in name: __a = name.replace('''prompts_visual_ln''' , '''prompts_visual_layernorm''' ) # mit if name == "mit.positional_embedding": __a = name.replace('''positional''' , '''position''' ) if name.startswith('''mit.resblocks''' ): __a = name.replace('''mit.resblocks''' , '''mit.encoder.layers''' ) # prompts generator if name.startswith('''prompts_generator.norm''' ): __a = name.replace('''prompts_generator.norm''' , '''prompts_generator.layernorm''' ) return name def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict ) -> List[Any]: '''simple docstring''' for key in orig_state_dict.copy().keys(): __a = orig_state_dict.pop(UpperCAmelCase__ ) if "attn.in_proj" in key: __a = key.split('''.''' ) if key.startswith('''visual''' ): __a = key_split[3] __a = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: __a = val[ :dim, : ] __a = val[ dim : dim * 2, : ] __a = val[ -dim:, : ] else: __a = val[ :dim ] __a = val[ dim : dim * 2 ] __a = val[ -dim: ] else: if "weight" in key: __a = val[ :dim, : ] __a = val[ dim : dim * 2, : ] __a = val[ -dim:, : ] else: __a = val[:dim] __a = val[ dim : dim * 2 ] __a = val[-dim:] elif key.startswith('''mit''' ): __a = key_split[2] __a = config.vision_config.mit_hidden_size if "weight" in key: __a = val[:dim, :] __a = val[dim : dim * 2, :] __a = val[-dim:, :] else: __a = val[:dim] __a = val[dim : dim * 2] __a = val[-dim:] else: __a = key_split[2] __a = config.text_config.hidden_size if "weight" in key: __a = val[:dim, :] __a = val[ dim : dim * 2, : ] __a = val[-dim:, :] else: __a = val[:dim] __a = val[ dim : dim * 2 ] __a = val[-dim:] else: __a = rename_key(UpperCAmelCase__ ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: __a = val.T __a = val return orig_state_dict def lowercase ( lowerCAmelCase__ : Optional[int] ) -> List[Any]: '''simple docstring''' if num_frames == 8: __a = """eating_spaghetti_8_frames.npy""" elif num_frames == 16: __a = """eating_spaghetti.npy""" elif num_frames == 32: __a = """eating_spaghetti_32_frames.npy""" __a = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''' , filename=UpperCAmelCase__ , repo_type='''dataset''' , ) __a = np.load(UpperCAmelCase__ ) return list(UpperCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any]=None , lowerCAmelCase__ : Any=False ) -> Union[str, Any]: '''simple docstring''' __a = { # fully supervised kinetics-400 checkpoints """xclip-base-patch32""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth""", """xclip-base-patch32-16-frames""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth""" ), """xclip-base-patch16""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth""", """xclip-base-patch16-16-frames""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth""" ), """xclip-large-patch14""": """https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb""", """xclip-large-patch14-16-frames""": """https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f""", # fully supervised kinetics-600 checkpoints """xclip-base-patch16-kinetics-600""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth""" ), """xclip-base-patch16-kinetics-600-16-frames""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth""" ), """xclip-large-patch14-kinetics-600""": """https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be""", # few shot """xclip-base-patch16-hmdb-2-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth""" ), """xclip-base-patch16-hmdb-4-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth""" ), """xclip-base-patch16-hmdb-8-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth""" ), """xclip-base-patch16-hmdb-16-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth""" ), """xclip-base-patch16-ucf-2-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth""" ), """xclip-base-patch16-ucf-4-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth""" ), """xclip-base-patch16-ucf-8-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth""" ), """xclip-base-patch16-ucf-16-shot""": ( """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth""" ), # zero shot """xclip-base-patch16-zero-shot""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth""", } __a = model_to_url[model_name] __a = 8 if "16-frames" in model_name: __a = 16 elif "shot" in model_name: __a = 32 __a = get_xclip_config(UpperCAmelCase__ , UpperCAmelCase__ ) __a = XCLIPModel(UpperCAmelCase__ ) model.eval() if "drive" in checkpoint_url: __a = """pytorch_model.bin""" gdown.cached_download(UpperCAmelCase__ , UpperCAmelCase__ , quiet=UpperCAmelCase__ ) __a = torch.load(UpperCAmelCase__ , map_location='''cpu''' )["""model"""] else: __a = torch.hub.load_state_dict_from_url(UpperCAmelCase__ )["""model"""] __a = convert_state_dict(UpperCAmelCase__ , UpperCAmelCase__ ) __a = XCLIPModel(UpperCAmelCase__ ) __a = model.load_state_dict(UpperCAmelCase__ , strict=UpperCAmelCase__ ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() __a = 336 if model_name == """xclip-large-patch14-16-frames""" else 224 __a = VideoMAEImageProcessor(size=UpperCAmelCase__ ) __a = CLIPTokenizer.from_pretrained('''openai/clip-vit-base-patch32''' ) __a = CLIPTokenizerFast.from_pretrained('''openai/clip-vit-base-patch32''' ) __a = XCLIPProcessor(image_processor=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ ) __a = prepare_video(UpperCAmelCase__ ) __a = processor( text=['''playing sports''', '''eating spaghetti''', '''go shopping'''] , videos=UpperCAmelCase__ , return_tensors='''pt''' , padding=UpperCAmelCase__ ) print('''Shape of pixel values:''' , inputs.pixel_values.shape ) with torch.no_grad(): __a = model(**UpperCAmelCase__ ) # Verify outputs __a = outputs.logits_per_video __a = logits_per_video.softmax(dim=1 ) print('''Probs:''' , UpperCAmelCase__ ) # kinetics-400 if model_name == "xclip-base-patch32": __a = torch.tensor([[0.00_19, 0.99_51, 0.00_30]] ) elif model_name == "xclip-base-patch32-16-frames": __a = torch.tensor([[7.0_9_9_9e-0_4, 9.9_8_8_3e-0_1, 4.5_5_8_0e-0_4]] ) elif model_name == "xclip-base-patch16": __a = torch.tensor([[0.00_83, 0.96_81, 0.02_36]] ) elif model_name == "xclip-base-patch16-16-frames": __a = torch.tensor([[7.6_9_3_7e-0_4, 9.9_7_2_8e-0_1, 1.9_4_7_3e-0_3]] ) elif model_name == "xclip-large-patch14": __a = torch.tensor([[0.00_62, 0.98_64, 0.00_75]] ) elif model_name == "xclip-large-patch14-16-frames": __a = torch.tensor([[3.3_8_7_7e-0_4, 9.9_9_3_7e-0_1, 2.8_8_8_8e-0_4]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": __a = torch.tensor([[0.05_55, 0.89_14, 0.05_31]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": __a = torch.tensor([[3.8_5_5_4e-0_4, 9.9_9_2_9e-0_1, 3.2_7_5_4e-0_4]] ) elif model_name == "xclip-large-patch14-kinetics-600": __a = torch.tensor([[0.00_36, 0.99_20, 0.00_45]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": __a = torch.tensor([[7.1_8_9_0e-0_6, 9.9_9_9_4e-0_1, 5.6_5_5_9e-0_5]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": __a = torch.tensor([[1.0_3_2_0e-0_5, 9.9_9_9_3e-0_1, 6.2_4_3_5e-0_5]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": __a = torch.tensor([[4.1_3_7_7e-0_6, 9.9_9_9_0e-0_1, 9.8_3_8_6e-0_5]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": __a = torch.tensor([[4.1_3_4_7e-0_5, 9.9_9_6_2e-0_1, 3.3_4_1_1e-0_4]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": __a = torch.tensor([[8.5_8_5_7e-0_5, 9.9_9_2_8e-0_1, 6.3_2_9_1e-0_4]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": __a = torch.tensor([[8.5_8_5_7e-0_5, 9.9_9_2_8e-0_1, 6.3_2_9_1e-0_4]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": __a = torch.tensor([[0.00_27, 0.99_04, 0.00_70]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": __a = torch.tensor([[9.8_2_1_9e-0_4, 9.9_5_9_3e-0_1, 3.0_8_6_3e-0_3]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": __a = torch.tensor([[3.5_0_8_2e-0_4, 9.9_7_8_5e-0_1, 1.7_9_6_6e-0_3]] ) else: raise ValueError(f'''Model name {model_name} not supported''' ) assert torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCAmelCase__ ) if push_to_hub: print('''Pushing model, processor and slow tokenizer files to the hub...''' ) model.push_to_hub(UpperCAmelCase__ , organization='''nielsr''' ) processor.push_to_hub(UpperCAmelCase__ , organization='''nielsr''' ) slow_tokenizer.push_to_hub(UpperCAmelCase__ , organization='''nielsr''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="xclip-base-patch32", type=str, help="Name of the model.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) lowercase_ = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
708
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable lowercase_ = {"configuration_gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["GPTNeoXTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXForCausalLM", "GPTNeoXForQuestionAnswering", "GPTNeoXForSequenceClassification", "GPTNeoXForTokenClassification", "GPTNeoXLayer", "GPTNeoXModel", "GPTNeoXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
65
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> Optional[int]: if b == 0: return 1 if (b % 2) == 0: return actual_power(_lowercase , int(b / 2 ) ) * actual_power(_lowercase , int(b / 2 ) ) else: return a * actual_power(_lowercase , int(b / 2 ) ) * actual_power(_lowercase , int(b / 2 ) ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> float: if b < 0: return 1 / actual_power(_lowercase , _lowercase ) return actual_power(_lowercase , _lowercase ) if __name__ == "__main__": print(power(-2, -3))
709
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=2 , _a=8 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=16 , _a=5 , _a=2 , _a=36 , _a="gelu" , _a=0.0 , _a=0.0 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self ): __a = self.get_config() __a = 300 return config def __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraModel(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a ) __a = model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = MraModel(_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , ) __a = model( _a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , ) __a = model(_a , attention_mask=_a , token_type_ids=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraForMaskedLM(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraForQuestionAnswering(config=_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , token_type_ids=_a , start_positions=_a , end_positions=_a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MraForSequenceClassification(_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MraForTokenClassification(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_choices __a = MraForMultipleChoice(config=_a ) model.to(_a ) model.eval() __a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) __UpperCAmelCase : str = False __UpperCAmelCase : Any = False __UpperCAmelCase : List[Any] = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Dict = () def __UpperCAmelCase ( self ): __a = MraModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a = type self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MraModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip(reason='''MRA does not output attentions''' ) def __UpperCAmelCase ( self ): return @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = MraModel.from_pretrained('''uw-madison/mra-base-512-4''' ) __a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4''' ) __a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = 50_265 __a = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3''' ) __a = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = 50_265 __a = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
65
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) lowercase_ = logging.getLogger(__name__) @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : int = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) __UpperCAmelCase : Union[str, Any] = field( default=UpperCAmelCase__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) __UpperCAmelCase : Dict = field( default=UpperCAmelCase__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) __UpperCAmelCase : int = field( default=UpperCAmelCase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) __UpperCAmelCase : str = field(default=UpperCAmelCase__ , metadata={'help': 'Whether tp freeze the encoder.'} ) __UpperCAmelCase : str = field(default=UpperCAmelCase__ , metadata={'help': 'Whether to freeze the embeddings.'} ) @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : str = field( metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'} ) __UpperCAmelCase : Tuple = field( default='summarization' , metadata={'help': 'Task name, summarization (or summarization_{dataset} for pegasus) or translation'} , ) __UpperCAmelCase : Dict = field( default=1_0_2_4 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __UpperCAmelCase : List[Any] = field( default=1_2_8 , metadata={ 'help': ( 'The maximum total sequence length for target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __UpperCAmelCase : Dict = field( default=1_4_2 , metadata={ 'help': ( 'The maximum total sequence length for validation target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded. ' 'This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ' 'during ``evaluate`` and ``predict``.' ) } , ) __UpperCAmelCase : Tuple = field( default=1_4_2 , metadata={ 'help': ( 'The maximum total sequence length for test target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __UpperCAmelCase : Any = field(default=-1 , metadata={'help': '# training examples. -1 means use all.'} ) __UpperCAmelCase : List[str] = field(default=-1 , metadata={'help': '# validation examples. -1 means use all.'} ) __UpperCAmelCase : str = field(default=-1 , metadata={'help': '# test examples. -1 means use all.'} ) __UpperCAmelCase : Tuple = field(default=UpperCAmelCase__ , metadata={'help': 'Source language id for translation.'} ) __UpperCAmelCase : Tuple = field(default=UpperCAmelCase__ , metadata={'help': 'Target language id for translation.'} ) __UpperCAmelCase : Optional[int] = field(default=UpperCAmelCase__ , metadata={'help': '# num_beams to use for evaluation.'} ) __UpperCAmelCase : Any = field( default=UpperCAmelCase__ , metadata={'help': 'If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'} , ) def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Optional[Any]: logger.info(f'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(f''' {key} = {metrics[key]}''' ) save_json(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , f'''{split}_results.json''' ) ) def lowercase ( ) -> Optional[int]: __a = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __a , __a , __a = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __a , __a , __a = parser.parse_args_into_dataclasses() check_output_dir(UpperCAmelCase__ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , UpperCAmelCase__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __a = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __a = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ): assert hasattr(UpperCAmelCase__ , UpperCAmelCase__ ), f'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(UpperCAmelCase__ , UpperCAmelCase__ , getattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) __a = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __a = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=UpperCAmelCase__ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(UpperCAmelCase__ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: __a = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(UpperCAmelCase__ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __a = tokenizer.lang_code_to_id[data_args.tgt_lang] else: __a = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(UpperCAmelCase__ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) __a = SeqaSeqDataset # Get datasets __a = ( dataset_class( UpperCAmelCase__ , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) __a = ( dataset_class( UpperCAmelCase__ , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) __a = ( dataset_class( UpperCAmelCase__ , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer __a = ( build_compute_metrics_fn(data_args.task , UpperCAmelCase__ ) if training_args.predict_with_generate else None ) __a = SeqaSeqTrainer( model=UpperCAmelCase__ , args=UpperCAmelCase__ , data_args=UpperCAmelCase__ , train_dataset=UpperCAmelCase__ , eval_dataset=UpperCAmelCase__ , data_collator=SeqaSeqDataCollator( UpperCAmelCase__ , UpperCAmelCase__ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , ) __a = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) __a = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) __a = train_result.metrics __a = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , UpperCAmelCase__ , training_args.output_dir ) all_metrics.update(UpperCAmelCase__ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __a = trainer.evaluate(metric_key_prefix='''val''' ) __a = data_args.n_val __a = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , UpperCAmelCase__ , training_args.output_dir ) all_metrics.update(UpperCAmelCase__ ) if training_args.do_predict: logger.info('''*** Predict ***''' ) __a = trainer.predict(test_dataset=UpperCAmelCase__ , metric_key_prefix='''test''' ) __a = test_output.metrics __a = data_args.n_test if trainer.is_world_process_zero(): __a = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , UpperCAmelCase__ , training_args.output_dir ) all_metrics.update(UpperCAmelCase__ ) if training_args.predict_with_generate: __a = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ ) __a = lmap(str.strip , UpperCAmelCase__ ) write_txt_file(UpperCAmelCase__ , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(UpperCAmelCase__ , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def lowercase ( lowerCAmelCase__ : Union[str, Any] ) -> List[Any]: main() if __name__ == "__main__": main()
710
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> list[str]: if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number_of_bytes!''' ) __a = number_of_bytes // partitions __a = [] for i in range(lowerCAmelCase__ ): __a = i * bytes_per_partition + 1 __a = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { "configuration_jukebox": [ "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "JukeboxConfig", "JukeboxPriorConfig", "JukeboxVQVAEConfig", ], "tokenization_jukebox": ["JukeboxTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST", "JukeboxModel", "JukeboxPreTrainedModel", "JukeboxVQVAE", "JukeboxPrior", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
711
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> list: __a = len(lowerCAmelCase__ ) __a = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): __a = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" import argparse import struct import unittest class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): __a = data # Initialize hash values __a = [ 0X6A09_E667, 0XBB67_AE85, 0X3C6E_F372, 0XA54F_F53A, 0X510E_527F, 0X9B05_688C, 0X1F83_D9AB, 0X5BE0_CD19, ] # Initialize round constants __a = [ 0X428A_2F98, 0X7137_4491, 0XB5C0_FBCF, 0XE9B5_DBA5, 0X3956_C25B, 0X59F1_11F1, 0X923F_82A4, 0XAB1C_5ED5, 0XD807_AA98, 0X1283_5B01, 0X2431_85BE, 0X550C_7DC3, 0X72BE_5D74, 0X80DE_B1FE, 0X9BDC_06A7, 0XC19B_F174, 0XE49B_69C1, 0XEFBE_4786, 0X0FC1_9DC6, 0X240C_A1CC, 0X2DE9_2C6F, 0X4A74_84AA, 0X5CB0_A9DC, 0X76F9_88DA, 0X983E_5152, 0XA831_C66D, 0XB003_27C8, 0XBF59_7FC7, 0XC6E0_0BF3, 0XD5A7_9147, 0X06CA_6351, 0X1429_2967, 0X27B7_0A85, 0X2E1B_2138, 0X4D2C_6DFC, 0X5338_0D13, 0X650A_7354, 0X766A_0ABB, 0X81C2_C92E, 0X9272_2C85, 0XA2BF_E8A1, 0XA81A_664B, 0XC24B_8B70, 0XC76C_51A3, 0XD192_E819, 0XD699_0624, 0XF40E_3585, 0X106A_A070, 0X19A4_C116, 0X1E37_6C08, 0X2748_774C, 0X34B0_BCB5, 0X391C_0CB3, 0X4ED8_AA4A, 0X5B9C_CA4F, 0X682E_6FF3, 0X748F_82EE, 0X78A5_636F, 0X84C8_7814, 0X8CC7_0208, 0X90BE_FFFA, 0XA450_6CEB, 0XBEF9_A3F7, 0XC671_78F2, ] __a = self.preprocessing(self.data ) self.final_hash() @staticmethod def __UpperCAmelCase ( _a ): __a = B'''\x80''' + (B'''\x00''' * (63 - (len(UpperCamelCase__ ) + 8) % 64)) __a = struct.pack('''>Q''' , (len(UpperCamelCase__ ) * 8) ) return data + padding + big_endian_integer def __UpperCAmelCase ( self ): __a = [ self.preprocessed_data[x : x + 64] for x in range(0 , len(self.preprocessed_data ) , 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __a = list(struct.unpack('''>16L''' , UpperCamelCase__ ) ) # add 48 0-ed integers words += [0] * 48 __a = self.hashes for index in range(0 , 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __a = ( self.ror(words[index - 15] , 7 ) ^ self.ror(words[index - 15] , 18 ) ^ (words[index - 15] >> 3) ) __a = ( self.ror(words[index - 2] , 17 ) ^ self.ror(words[index - 2] , 19 ) ^ (words[index - 2] >> 10) ) __a = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_0000_0000 # Compression __a = self.ror(UpperCamelCase__ , 6 ) ^ self.ror(UpperCamelCase__ , 11 ) ^ self.ror(UpperCamelCase__ , 25 ) __a = (e & f) ^ ((~e & 0XFFFF_FFFF) & g) __a = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0000_0000 __a = self.ror(UpperCamelCase__ , 2 ) ^ self.ror(UpperCamelCase__ , 13 ) ^ self.ror(UpperCamelCase__ , 22 ) __a = (a & b) ^ (a & c) ^ (b & c) __a = (sa + maj) % 0X1_0000_0000 __a = ( g, f, e, ((d + tempa) % 0X1_0000_0000), c, b, a, ((tempa + tempa) % 0X1_0000_0000), ) __a = [a, b, c, d, e, f, g, h] # Modify final values __a = [ ((element + mutated_hash_values[index]) % 0X1_0000_0000) for index, element in enumerate(self.hashes ) ] __a = ''''''.join([hex(UpperCamelCase__ )[2:].zfill(8 ) for value in self.hashes] ) def __UpperCAmelCase ( self , _a , _a ): return 0XFFFF_FFFF & (value << (32 - rotations)) | (value >> rotations) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): import hashlib __a = bytes('''Test String''' , '''utf-8''' ) self.assertEqual(SHAaaa(UpperCamelCase__ ).hash , hashlib.shaaaa(UpperCamelCase__ ).hexdigest() ) def lowercase ( ) -> Dict: import doctest doctest.testmod() __a = argparse.ArgumentParser() parser.add_argument( '''-s''' , '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument( '''-f''' , '''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) __a = parser.parse_args() __a = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: __a = f.read() else: __a = bytes(_lowercase , '''utf-8''' ) print(SHAaaa(_lowercase ).hash ) if __name__ == "__main__": main()
712
"""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 lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} lowercase_ = { "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" ), }, } lowercase_ = { "allenai/longformer-base-4096": 4_0_9_6, "allenai/longformer-large-4096": 4_0_9_6, "allenai/longformer-large-4096-finetuned-triviaqa": 4_0_9_6, "allenai/longformer-base-4096-extra.pos.embd.only": 4_0_9_6, "allenai/longformer-large-4096-extra.pos.embd.only": 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowercase ( ) -> Union[str, Any]: __a = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __a = bs[:] __a = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCAmelCase__ ) cs.append(2**8 + n ) n += 1 __a = [chr(lowerCAmelCase__ ) for n in cs] return dict(zip(lowerCAmelCase__ , lowerCAmelCase__ ) ) def lowercase ( lowerCAmelCase__ : Tuple ) -> Tuple: __a = set() __a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __a = char return pairs class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = VOCAB_FILES_NAMES __UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Union[str, Any] = ['input_ids', 'attention_mask'] def __init__( self , _a , _a , _a="replace" , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=False , **_a , ): __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else bos_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else sep_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else cls_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( errors=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , **_a , ) with open(_a , encoding='''utf-8''' ) as vocab_handle: __a = json.load(_a ) __a = {v: k for k, v in self.encoder.items()} __a = errors # how to handle errors in decoding __a = bytes_to_unicode() __a = {v: k for k, v in self.byte_encoder.items()} with open(_a , encoding='''utf-8''' ) as merges_handle: __a = merges_handle.read().split('''\n''' )[1:-1] __a = [tuple(merge.split() ) for merge in bpe_merges] __a = dict(zip(_a , range(len(_a ) ) ) ) __a = {} __a = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __a = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def __UpperCAmelCase ( self ): return len(self.encoder ) def __UpperCAmelCase ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def __UpperCAmelCase ( self , _a ): if token in self.cache: return self.cache[token] __a = tuple(_a ) __a = get_pairs(_a ) if not pairs: return token while True: __a = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __a , __a = bigram __a = [] __a = 0 while i < len(_a ): try: __a = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __a = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __a = tuple(_a ) __a = new_word if len(_a ) == 1: break else: __a = get_pairs(_a ) __a = ''' '''.join(_a ) __a = word return word def __UpperCAmelCase ( self , _a ): __a = [] for token in re.findall(self.pat , _a ): __a = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(''' ''' ) ) return bpe_tokens def __UpperCAmelCase ( self , _a ): return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def __UpperCAmelCase ( self , _a ): return self.decoder.get(_a ) def __UpperCAmelCase ( self , _a ): __a = ''''''.join(_a ) __a = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def __UpperCAmelCase ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_a , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '''\n''' ) __a = 0 with open(_a , '''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 _a : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __a = token_index writer.write(''' '''.join(_a ) + '''\n''' ) index += 1 return vocab_file, merge_file def __UpperCAmelCase ( self , _a , _a = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __a = [self.cls_token_id] __a = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __UpperCAmelCase ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self , _a , _a=False , **_a ): __a = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): __a = ''' ''' + text return (text, kwargs)
65
0
"""simple docstring""" import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = MgpstrTokenizer __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : Any = {} __UpperCAmelCase : List[Any] = False def __UpperCAmelCase ( self ): super().setUp() # fmt: off __a = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z'''] # fmt: on __a = dict(zip(_SCREAMING_SNAKE_CASE , range(len(_SCREAMING_SNAKE_CASE ) ) ) ) __a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(_SCREAMING_SNAKE_CASE ) + '''\n''' ) def __UpperCAmelCase ( self , **_a ): return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self , _a ): __a = '''tester''' __a = '''tester''' return input_text, output_text @unittest.skip('''MGP-STR always lower cases letters.''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = self.get_tokenizers(do_lower_case=_SCREAMING_SNAKE_CASE ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __a = '''[SPECIAL_TOKEN]''' tokenizer.add_special_tokens({'''cls_token''': special_token} ) __a = tokenizer.encode([special_token] , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 1 ) __a = tokenizer.decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertTrue(special_token not in decoded ) def __UpperCAmelCase ( self ): __a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __a , __a = self.get_input_output_texts(_SCREAMING_SNAKE_CASE ) __a = tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) __a = tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) __a = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a = tokenizer.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ) self.assertNotEqual(len(_SCREAMING_SNAKE_CASE ) , 0 ) __a = tokenizer.decode(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(text_a.replace(''' ''' , '''''' ) , _SCREAMING_SNAKE_CASE ) @unittest.skip('''MGP-STR tokenizer only handles one sequence.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''' ) def __UpperCAmelCase ( self ): pass
713
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "unc-nlp/lxmert-base-uncased": "https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = 'lxmert' __UpperCAmelCase : str = {} def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=9_500 , _a=1_600 , _a=400 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=9 , _a=5 , _a=5 , _a=2_048 , _a=4 , _a=6.67 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=True , _a=True , **_a , ): __a = vocab_size __a = hidden_size __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = num_qa_labels __a = num_object_labels __a = num_attr_labels __a = l_layers __a = x_layers __a = r_layers __a = visual_feat_dim __a = visual_pos_dim __a = visual_loss_normalizer __a = task_matched __a = task_mask_lm __a = task_obj_predict __a = task_qa __a = visual_obj_loss __a = visual_attr_loss __a = visual_feat_loss __a = {'''vision''': r_layers, '''cross_encoder''': x_layers, '''language''': l_layers} super().__init__(**_a )
65
0
"""simple docstring""" from __future__ import annotations import time lowercase_ = list[tuple[int, int]] lowercase_ = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowercase_ = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a ): __a = pos_x __a = pos_y __a = (pos_y, pos_x) __a = goal_x __a = goal_y __a = parent class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a ): __a = Node(start[1] , start[0] , goal[1] , goal[0] , _a ) __a = Node(goal[1] , goal[0] , goal[1] , goal[0] , _a ) __a = [self.start] __a = False def __UpperCAmelCase ( self ): while self.node_queue: __a = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: __a = True return self.retrace_path(_a ) __a = self.get_successors(_a ) for node in successors: self.node_queue.append(_a ) if not self.reached: return [self.start.pos] return None def __UpperCAmelCase ( self , _a ): __a = [] for action in delta: __a = parent.pos_x + action[1] __a = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_a ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(_a , _a , self.target.pos_y , self.target.pos_x , _a ) ) return successors def __UpperCAmelCase ( self , _a ): __a = node __a = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __a = current_node.parent path.reverse() return path class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a ): __a = BreadthFirstSearch(_a , _a ) __a = BreadthFirstSearch(_a , _a ) __a = False def __UpperCAmelCase ( self ): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __a = self.fwd_bfs.node_queue.pop(0 ) __a = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: __a = True return self.retrace_bidirectional_path( _a , _a ) __a = current_bwd_node __a = current_fwd_node __a = { self.fwd_bfs: self.fwd_bfs.get_successors(_a ), self.bwd_bfs: self.bwd_bfs.get_successors(_a ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(_a ) if not self.reached: return [self.fwd_bfs.start.pos] return None def __UpperCAmelCase ( self , _a , _a ): __a = self.fwd_bfs.retrace_path(_a ) __a = self.bwd_bfs.retrace_path(_a ) bwd_path.pop() bwd_path.reverse() __a = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() lowercase_ = (0, 0) lowercase_ = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) lowercase_ = time.time() lowercase_ = BreadthFirstSearch(init, goal) lowercase_ = bfs.search() lowercase_ = time.time() - start_bfs_time print("Unidirectional BFS computation time : ", bfs_time) lowercase_ = time.time() lowercase_ = BidirectionalBreadthFirstSearch(init, goal) lowercase_ = bd_bfs.search() lowercase_ = time.time() - start_bd_bfs_time print("Bidirectional BFS computation time : ", bd_bfs_time)
714
"""simple docstring""" import itertools import math def lowercase ( lowerCAmelCase__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( ) -> int: __a = 2 while True: if is_prime(lowerCAmelCase__ ): yield num num += 1 def lowercase ( lowerCAmelCase__ : int = 10001 ) -> int: return next(itertools.islice(prime_generator() , nth - 1 , lowerCAmelCase__ ) ) if __name__ == "__main__": print(F'''{solution() = }''')
65
0
"""simple docstring""" import pickle import numpy as np from matplotlib import pyplot as plt class __lowerCAmelCase : def __init__( self , _a , _a , _a , _a , _a , _a=0.2 , _a=0.2 ): __a = bp_numa __a = bp_numa __a = bp_numa __a = conva_get[:2] __a = conva_get[2] __a = size_pa __a = rate_w __a = rate_t __a = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] __a = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) __a = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) __a = -2 * np.random.rand(self.conva[1] ) + 1 __a = -2 * np.random.rand(self.num_bpa ) + 1 __a = -2 * np.random.rand(self.num_bpa ) + 1 def __UpperCAmelCase ( self , _a ): # save model dict with pickle __a = { '''num_bp1''': self.num_bpa, '''num_bp2''': self.num_bpa, '''num_bp3''': self.num_bpa, '''conv1''': self.conva, '''step_conv1''': self.step_conva, '''size_pooling1''': self.size_poolinga, '''rate_weight''': self.rate_weight, '''rate_thre''': self.rate_thre, '''w_conv1''': self.w_conva, '''wkj''': self.wkj, '''vji''': self.vji, '''thre_conv1''': self.thre_conva, '''thre_bp2''': self.thre_bpa, '''thre_bp3''': self.thre_bpa, } with open(__lowercase , '''wb''' ) as f: pickle.dump(__lowercase , __lowercase ) print(f'''Model saved: {save_path}''' ) @classmethod def __UpperCAmelCase ( cls , _a ): # read saved model with open(__lowercase , '''rb''' ) as f: __a = pickle.load(__lowercase ) # noqa: S301 __a = model_dic.get('''conv1''' ) conv_get.append(model_dic.get('''step_conv1''' ) ) __a = model_dic.get('''size_pooling1''' ) __a = model_dic.get('''num_bp1''' ) __a = model_dic.get('''num_bp2''' ) __a = model_dic.get('''num_bp3''' ) __a = model_dic.get('''rate_weight''' ) __a = model_dic.get('''rate_thre''' ) # create model instance __a = CNN(__lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) # modify model parameter __a = model_dic.get('''w_conv1''' ) __a = model_dic.get('''wkj''' ) __a = model_dic.get('''vji''' ) __a = model_dic.get('''thre_conv1''' ) __a = model_dic.get('''thre_bp2''' ) __a = model_dic.get('''thre_bp3''' ) return conv_ins def __UpperCAmelCase ( self , _a ): return 1 / (1 + np.exp(-1 * x )) def __UpperCAmelCase ( self , _a ): return round(__lowercase , 3 ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): # convolution process __a = convs[0] __a = convs[1] __a = np.shape(__lowercase )[0] # get the data slice of original image data, data_focus __a = [] for i_focus in range(0 , size_data - size_conv + 1 , __lowercase ): for j_focus in range(0 , size_data - size_conv + 1 , __lowercase ): __a = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(__lowercase ) # calculate the feature map of every single kernel, and saved as list of matrix __a = [] __a = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(__lowercase ): __a = [] for i_focus in range(len(__lowercase ) ): __a = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(__lowercase ) ) __a = np.asmatrix(__lowercase ).reshape( __lowercase , __lowercase ) data_featuremap.append(__lowercase ) # expanding the data slice to One dimenssion __a = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(__lowercase ) ) __a = np.asarray(__lowercase ) return focus_list, data_featuremap def __UpperCAmelCase ( self , _a , _a , _a="average_pool" ): # pooling process __a = len(featuremaps[0] ) __a = int(size_map / size_pooling ) __a = [] for i_map in range(len(__lowercase ) ): __a = featuremaps[i_map] __a = [] for i_focus in range(0 , __lowercase , __lowercase ): for j_focus in range(0 , __lowercase , __lowercase ): __a = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(__lowercase ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(__lowercase ) ) __a = np.asmatrix(__lowercase ).reshape(__lowercase , __lowercase ) featuremap_pooled.append(__lowercase ) return featuremap_pooled def __UpperCAmelCase ( self , _a ): # expanding three dimension data to one dimension list __a = [] for i in range(len(__lowercase ) ): __a = np.shape(data[i] ) __a = data[i].reshape(1 , shapes[0] * shapes[1] ) __a = data_listed.getA().tolist()[0] data_expanded.extend(__lowercase ) __a = np.asarray(__lowercase ) return data_expanded def __UpperCAmelCase ( self , _a ): # expanding matrix to one dimension list __a = np.asarray(__lowercase ) __a = np.shape(__lowercase ) __a = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): __a = [] __a = 0 for i_map in range(__lowercase ): __a = np.ones((size_map, size_map) ) for i in range(0 , __lowercase , __lowercase ): for j in range(0 , __lowercase , __lowercase ): __a = pd_pool[ i_pool ] __a = i_pool + 1 __a = np.multiply( __lowercase , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(__lowercase ) return pd_all def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a=bool ): # model traning print('''----------------------Start Training-------------------------''' ) print((''' - - Shape: Train_Data ''', np.shape(__lowercase )) ) print((''' - - Shape: Teach_Data ''', np.shape(__lowercase )) ) __a = 0 __a = [] __a = 10_000 while rp < n_repeat and mse >= error_accuracy: __a = 0 print(f'''-------------Learning Time {rp}--------------''' ) for p in range(len(__lowercase ) ): # print('------------Learning Image: %d--------------'%p) __a = np.asmatrix(datas_train[p] ) __a = np.asarray(datas_teach[p] ) __a , __a = self.convolute( __lowercase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) __a = self.pooling(__lowercase , self.size_poolinga ) __a = np.shape(__lowercase ) __a = self._expand(__lowercase ) __a = data_bp_input __a = np.dot(__lowercase , self.vji.T ) - self.thre_bpa __a = self.sig(__lowercase ) __a = np.dot(__lowercase , self.wkj.T ) - self.thre_bpa __a = self.sig(__lowercase ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- __a = np.multiply( (data_teach - bp_outa) , np.multiply(__lowercase , (1 - bp_outa) ) ) __a = np.multiply( np.dot(__lowercase , self.wkj ) , np.multiply(__lowercase , (1 - bp_outa) ) ) __a = np.dot(__lowercase , self.vji ) __a = pd_i_all / (self.size_poolinga * self.size_poolinga) __a = pd_conva_pooled.T.getA().tolist() __a = self._calculate_gradient_from_pool( __lowercase , __lowercase , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): __a = self._expand_mat(pd_conva_all[k_conv] ) __a = self.rate_weight * np.dot(__lowercase , __lowercase ) __a = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) __a = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer __a = self.wkj + pd_k_all.T * bp_outa * self.rate_weight __a = self.vji + pd_j_all.T * bp_outa * self.rate_weight __a = self.thre_bpa - pd_k_all * self.rate_thre __a = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image __a = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) __a = rp + 1 __a = error_count / patterns all_mse.append(__lowercase ) def draw_error(): __a = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(__lowercase , '''+-''' ) plt.plot(__lowercase , '''r--''' ) plt.xlabel('''Learning Times''' ) plt.ylabel('''All_mse''' ) plt.grid(__lowercase , alpha=0.5 ) plt.show() print('''------------------Training Complished---------------------''' ) print((''' - - Training epoch: ''', rp, f''' - - Mse: {mse:.6f}''') ) if draw_e: draw_error() return mse def __UpperCAmelCase ( self , _a ): # model predict __a = [] print('''-------------------Start Testing-------------------------''' ) print((''' - - Shape: Test_Data ''', np.shape(__lowercase )) ) for p in range(len(__lowercase ) ): __a = np.asmatrix(datas_test[p] ) __a , __a = self.convolute( __lowercase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) __a = self.pooling(__lowercase , self.size_poolinga ) __a = self._expand(__lowercase ) __a = data_bp_input __a = bp_outa * self.vji.T - self.thre_bpa __a = self.sig(__lowercase ) __a = bp_outa * self.wkj.T - self.thre_bpa __a = self.sig(__lowercase ) produce_out.extend(bp_outa.getA().tolist() ) __a = [list(map(self.do_round , __lowercase ) ) for each in produce_out] return np.asarray(__lowercase ) def __UpperCAmelCase ( self , _a ): # return the data of image after convoluting process so we can check it out __a = np.asmatrix(__lowercase ) __a , __a = self.convolute( __lowercase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) __a = self.pooling(__lowercase , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
715
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase_ = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
65
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """xlm-mlm-en-2048""": """https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json""", """xlm-mlm-ende-1024""": """https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json""", """xlm-mlm-enfr-1024""": """https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json""", """xlm-mlm-enro-1024""": """https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json""", """xlm-mlm-tlm-xnli15-1024""": """https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json""", """xlm-mlm-xnli15-1024""": """https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json""", """xlm-clm-enfr-1024""": """https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json""", """xlm-clm-ende-1024""": """https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json""", """xlm-mlm-17-1280""": """https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json""", """xlm-mlm-100-1280""": """https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json""", } class __lowerCAmelCase ( __snake_case ): '''simple docstring''' __UpperCAmelCase : Dict = 'xlm' __UpperCAmelCase : Dict = { 'hidden_size': 'emb_dim', 'num_attention_heads': 'n_heads', 'num_hidden_layers': 'n_layers', 'n_words': 'vocab_size', # For backward compatibility } def __init__( self , _a=30_145 , _a=2_048 , _a=12 , _a=16 , _a=0.1 , _a=0.1 , _a=True , _a=False , _a=False , _a=False , _a=1 , _a=True , _a=512 , _a=2_048**-0.5 , _a=1E-12 , _a=0.02 , _a=0 , _a=1 , _a=2 , _a=3 , _a=5 , _a=True , _a="first" , _a=True , _a=None , _a=True , _a=0.1 , _a=5 , _a=5 , _a=0 , _a=0 , _a=2 , _a=0 , **_a , ): __a = vocab_size __a = emb_dim __a = n_layers __a = n_heads __a = dropout __a = attention_dropout __a = gelu_activation __a = sinusoidal_embeddings __a = causal __a = asm __a = n_langs __a = use_lang_emb __a = layer_norm_eps __a = bos_index __a = eos_index __a = pad_index __a = unk_index __a = mask_index __a = is_encoder __a = max_position_embeddings __a = embed_init_std __a = init_std __a = summary_type __a = summary_use_proj __a = summary_activation __a = summary_proj_to_labels __a = summary_first_dropout __a = start_n_top __a = end_n_top __a = mask_token_id __a = lang_id if "n_words" in kwargs: __a = kwargs["n_words"] super().__init__(pad_token_id=A_ , bos_token_id=A_ , **A_ ) class __lowerCAmelCase ( __snake_case ): '''simple docstring''' @property def __UpperCAmelCase ( self ): if self.task == "multiple-choice": __a = {0: "batch", 1: "choice", 2: "sequence"} else: __a = {0: "batch", 1: "sequence"} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
716
"""simple docstring""" from sklearn.metrics import fa_score import datasets lowercase_ = "\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n" lowercase_ = "\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {'f1': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results['f1'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results['f1'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n >>> print(round(results['f1'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'f1': array([0.8, 0. , 0. ])}\n" lowercase_ = "\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def __UpperCAmelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'''] , ) def __UpperCAmelCase ( self , _a , _a , _a=None , _a=1 , _a="binary" , _a=None ): __a = fa_score( _a , _a , labels=_a , pos_label=_a , average=_a , sample_weight=_a ) return {"f1": float(_a ) if score.size == 1 else score}
65
0
"""simple docstring""" from itertools import product def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: __a = sides_number __a = max_face_number * dice_number __a = [0] * (max_total + 1) __a = 1 __a = range(lowerCAmelCase__ , max_face_number + 1 ) for dice_numbers in product(lowerCAmelCase__ , repeat=lowerCAmelCase__ ): __a = sum(lowerCAmelCase__ ) totals_frequencies[total] += 1 return totals_frequencies def lowercase ( ) -> List[str]: __a = total_frequency_distribution( sides_number=4 , dice_number=9 ) __a = total_frequency_distribution( sides_number=6 , dice_number=6 ) __a = 0 __a = 9 __a = 4 * 9 __a = 6 for peter_total in range(lowerCAmelCase__ , max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) __a = (4**9) * (6**6) __a = peter_wins_count / total_games_number __a = round(lowerCAmelCase__ , ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(F'''{solution() = }''')
717
"""simple docstring""" from ..utils import DummyObject, requires_backends class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = ['onnx'] def __init__( self , *_a , **_a ): requires_backends(self , ['''onnx'''] ) @classmethod def __UpperCAmelCase ( cls , *_a , **_a ): requires_backends(cls , ['''onnx'''] ) @classmethod def __UpperCAmelCase ( cls , *_a , **_a ): requires_backends(cls , ['''onnx'''] )
65
0
"""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.models.esm.modeling_esmfold import EsmForProteinFolding class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=False , _a=True , _a=False , _a=False , _a=19 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): __a = EsmConfig( vocab_size=33 , 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 , is_folding_model=lowerCamelCase__ , esmfold_config={'''trunk''': {'''num_blocks''': 2}, '''fp16_esm''': False} , ) return config def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = EsmForProteinFolding(config=lowerCamelCase__ ).float() model.to(lowerCamelCase__ ) model.eval() __a = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ ) __a = model(lowerCamelCase__ ) __a = model(lowerCamelCase__ ) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 14, 3) ) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( __a ) = config_and_inputs __a = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = False __UpperCAmelCase : Union[str, Any] = (EsmForProteinFolding,) if is_torch_available() else () __UpperCAmelCase : Optional[Any] = () __UpperCAmelCase : str = {} if is_torch_available() else {} __UpperCAmelCase : str = False def __UpperCAmelCase ( self ): __a = EsmFoldModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase__ , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) @unittest.skip('''Does not support attention outputs''' ) def __UpperCAmelCase ( self ): pass @unittest.skip def __UpperCAmelCase ( self ): pass @unittest.skip('''Esm does not support embedding resizing''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Esm does not support embedding resizing''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold does not support passing input embeds!''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold does not support head pruning.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold does not support head pruning.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold does not support head pruning.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold does not support head pruning.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold does not support head pruning.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold does not output hidden states in the normal way.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMfold does not output hidden states in the normal way.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold only has one output format.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''This test doesn\'t work for ESMFold and doesn\'t test core functionality''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold does not support input chunking.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''ESMFold doesn\'t support data parallel.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @require_torch class __lowerCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = EsmForProteinFolding.from_pretrained('''facebook/esmfold_v1''' ).float() model.eval() __a = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __a = model(lowerCamelCase__ )["positions"] __a = torch.tensor([2.5828, 0.7993, -10.9_334] , dtype=torch.floataa ) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , lowerCamelCase__ , atol=1E-4 ) )
718
"""simple docstring""" import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin lowercase_ = 1e-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=16 , _a=13 , _a=7 , _a=14 , _a=10 , _a=19 , _a=5 , _a=4 , _a=True , _a=16 , _a=2 , _a=4 , _a=4 , _a="gelu" , _a=0.1 , _a=0.1 , _a=[1, 2, 3, 4, 5] , _a=25 , _a=5 , ): __a = d_model __a = parent __a = batch_size __a = prediction_length __a = context_length __a = cardinality __a = num_time_features __a = lags_sequence __a = embedding_dimension __a = is_training __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = context_length __a = prediction_length + label_length __a = label_length __a = moving_average __a = autocorrelation_factor def __UpperCAmelCase ( self ): return AutoformerConfig( d_model=self.d_model , 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 , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def __UpperCAmelCase ( self , _a ): __a = config.context_length + max(config.lags_sequence ) __a = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) __a = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) __a = floats_tensor([self.batch_size, _past_length] ) __a = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs __a = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) __a = floats_tensor([self.batch_size, config.prediction_length] ) __a = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def __UpperCAmelCase ( self ): __a = self.get_config() __a = self.prepare_autoformer_inputs_dict(_a ) return config, inputs_dict def __UpperCAmelCase ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def __UpperCAmelCase ( self , _a , _a ): __a = AutoformerModel(config=_a ).to(_a ).eval() __a = model(**_a ) __a = outputs.encoder_last_hidden_state __a = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: __a = model.get_encoder() encoder.save_pretrained(_a ) __a = AutoformerEncoder.from_pretrained(_a ).to(_a ) __a , __a , __a , __a , __a = model.create_network_inputs(**_a ) __a , __a = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) __a = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) __a = encoder(inputs_embeds=_a )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) __a = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) __a = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) __a = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) __a = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: __a = model.get_decoder() decoder.save_pretrained(_a ) __a = AutoformerDecoder.from_pretrained(_a ).to(_a ) __a = decoder( trend=_a , inputs_embeds=_a , encoder_hidden_states=_a , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Any = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () __UpperCAmelCase : int = (AutoformerForPrediction,) if is_torch_available() else () __UpperCAmelCase : Any = {'feature-extraction': AutoformerModel} if is_torch_available() else {} __UpperCAmelCase : int = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : int = False __UpperCAmelCase : Any = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : int = False def __UpperCAmelCase ( self ): __a = AutoformerModelTester(self ) __a = ConfigTester(self , config_class=_a , has_text_modality=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: __a = model_class(_a ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_a ) __a , __a = model_class.from_pretrained(_a , output_loading_info=_a ) self.assertEqual(info['''missing_keys'''] , [] ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*_a ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = inspect.signature(getattr(_a , '''forward''' ) ) # The main input is the name of the argument after `self` __a = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''' ) expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ] ) self.assertListEqual(arg_names[: len(_a )] , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True __a = getattr(self.model_tester , '''seq_length''' , _a ) __a = getattr(self.model_tester , '''decoder_seq_length''' , _a ) __a = getattr(self.model_tester , '''encoder_seq_length''' , _a ) __a = getattr(self.model_tester , '''d_model''' , _a ) __a = getattr(self.model_tester , '''num_attention_heads''' , _a ) __a = d_model // num_attention_heads for model_class in self.all_model_classes: __a = True __a = False __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.encoder_attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) __a = len(_a ) __a = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(_a , _a ) # decoder attentions __a = outputs.decoder_attentions self.assertIsInstance(_a , (list, tuple) ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions __a = outputs.cross_attentions self.assertIsInstance(_a , (list, tuple) ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine __a = True __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + 2 , len(_a ) ) __a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def __UpperCAmelCase ( self ): super().test_retain_grad_hidden_states_attentions() def lowercase ( lowerCAmelCase__ : Optional[int]="train-batch.pt" ) -> List[str]: __a = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=lowerCAmelCase__ , repo_type='''dataset''' ) __a = torch.load(lowerCAmelCase__ , map_location=lowerCAmelCase__ ) return batch @require_torch @slow class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch() with torch.no_grad(): __a = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] __a = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=_a ) self.assertTrue(torch.allclose(output[0, :3, :3] , _a , atol=_a ) ) def __UpperCAmelCase ( self ): __a = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): __a = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state __a = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=_a ) self.assertTrue(torch.allclose(output[0, :3, :3] , _a , atol=_a ) ) def __UpperCAmelCase ( self ): __a = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): __a = model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) __a = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , _a ) __a = torch.tensor([3130.6763, 4056.5293, 7053.0786] , device=_a ) __a = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , _a , rtol=1E-1 ) )
65
0
"""simple docstring""" import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() lowercase_ : Optional[int] = logging.get_logger(__name__) def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[Any]: __a = torch.load(lowercase__ , map_location='''cpu''' ) if "model" in sd.keys(): __a = torch.load(lowercase__ , map_location='''cpu''' )['''model'''] # pop unnecessary weights __a = [ '''decoder.version''', '''decoder.output_projection.weight''', ] for key in keys_to_delete: if key in sd: sd.pop(lowercase__ ) __a = { '''decoder.project_in_dim.weight''': '''decoder.project_in.weight''', '''decoder.project_out_dim.weight''': '''decoder.project_out.weight''', '''decoder.layer_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.layer_norm.bias''': '''decoder.final_layer_norm.bias''', } for old_key, new_key in keys_to_rename.items(): if old_key in sd: __a = sd.pop(lowercase__ ) __a = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: __a = sd[key] # We split QKV in separate Q,K,V __a = key.replace('''.qkv_proj.''' , '''.q_proj.''' ) __a = key.replace('''.qkv_proj.''' , '''.k_proj.''' ) __a = key.replace('''.qkv_proj.''' , '''.v_proj.''' ) __a = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 __a , __a , __a = torch.split(lowercase__ , depth // 3 , dim=0 ) __a = q __a = k __a = v del sd[key] return sd @torch.no_grad() def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[Any]=None ) -> int: __a = load_checkpoint(lowercase__ ) if config is not None: __a = OPTConfig.from_pretrained(lowercase__ ) else: __a = OPTConfig() __a = OPTModel(lowercase__ ).half().eval() model.load_state_dict(lowercase__ ) # Check results Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) model.save_pretrained(lowercase__ ) if __name__ == "__main__": lowercase_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fairseq_path", type=str, help=( "path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:" " https://huggingface.co/models?other=opt_metasq" ), ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--hf_config", default=None, type=str, help="Define HF config.") lowercase_ : Optional[Any] = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
719
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str] ) -> Any: if isinstance(lowerCAmelCase__ , torch.Tensor ): return image elif isinstance(lowerCAmelCase__ , PIL.Image.Image ): __a = [image] if isinstance(image[0] , PIL.Image.Image ): __a = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] __a = np.concatenate(lowerCAmelCase__ , axis=0 ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 2_55.0 __a = image.transpose(0 , 3 , 1 , 2 ) __a = 2.0 * image - 1.0 __a = torch.from_numpy(lowerCAmelCase__ ) elif isinstance(image[0] , torch.Tensor ): __a = torch.cat(lowerCAmelCase__ , dim=0 ) return image def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[int]=0.99_95 ) -> int: if not isinstance(lowerCAmelCase__ , np.ndarray ): __a = True __a = va.device __a = va.cpu().numpy() __a = va.cpu().numpy() __a = np.sum(va * va / (np.linalg.norm(lowerCAmelCase__ ) * np.linalg.norm(lowerCAmelCase__ )) ) if np.abs(lowerCAmelCase__ ) > DOT_THRESHOLD: __a = (1 - t) * va + t * va else: __a = np.arccos(lowerCAmelCase__ ) __a = np.sin(lowerCAmelCase__ ) __a = theta_a * t __a = np.sin(lowerCAmelCase__ ) __a = np.sin(theta_a - theta_t ) / sin_theta_a __a = sin_theta_t / sin_theta_a __a = sa * va + sa * va if inputs_are_torch: __a = torch.from_numpy(lowerCAmelCase__ ).to(lowerCAmelCase__ ) return va def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[Any] ) -> int: __a = F.normalize(lowerCAmelCase__ , dim=-1 ) __a = F.normalize(lowerCAmelCase__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ) -> List[str]: for param in model.parameters(): __a = value class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a=None , _a=None , _a=None , ): super().__init__() self.register_modules( vae=_a , text_encoder=_a , clip_model=_a , tokenizer=_a , unet=_a , scheduler=_a , feature_extractor=_a , coca_model=_a , coca_tokenizer=_a , coca_transform=_a , ) __a = ( feature_extractor.size if isinstance(feature_extractor.size , _a ) else feature_extractor.size['''shortest_edge'''] ) __a = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , _a ) set_requires_grad(self.clip_model , _a ) def __UpperCAmelCase ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def __UpperCAmelCase ( self ): self.enable_attention_slicing(_a ) def __UpperCAmelCase ( self ): set_requires_grad(self.vae , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.vae , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.unet , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.unet , _a ) def __UpperCAmelCase ( self , _a , _a , _a ): # get the original timestep using init_timestep __a = min(int(num_inference_steps * strength ) , _a ) __a = max(num_inference_steps - init_timestep , 0 ) __a = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a=None ): if not isinstance(_a , torch.Tensor ): raise ValueError(f'''`image` has to be of type `torch.Tensor` but is {type(_a )}''' ) __a = image.to(device=_a , dtype=_a ) if isinstance(_a , _a ): __a = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_a ) ] __a = torch.cat(_a , dim=0 ) else: __a = self.vae.encode(_a ).latent_dist.sample(_a ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 0.1_8215 * init_latents __a = init_latents.repeat_interleave(_a , dim=0 ) __a = randn_tensor(init_latents.shape , generator=_a , device=_a , dtype=_a ) # get latents __a = self.scheduler.add_noise(_a , _a , _a ) __a = init_latents return latents def __UpperCAmelCase ( self , _a ): __a = self.coca_transform(_a ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): __a = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) __a = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def __UpperCAmelCase ( self , _a , _a ): __a = self.feature_extractor.preprocess(_a ) __a = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() __a = self.clip_model.get_image_features(_a ) __a = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_a ) __a = image_embeddings_clip.repeat_interleave(_a , dim=0 ) return image_embeddings_clip @torch.enable_grad() def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): __a = latents.detach().requires_grad_() __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a , encoder_hidden_states=_a ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): __a = self.scheduler.alphas_cumprod[timestep] __a = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __a = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 __a = torch.sqrt(_a ) __a = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , _a ): __a = self.scheduler.sigmas[index] __a = latents - sigma * noise_pred else: raise ValueError(f'''scheduler type {type(self.scheduler )} not supported''' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 1 / 0.1_8215 * sample __a = self.vae.decode(_a ).sample __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = transforms.Resize(self.feature_extractor_size )(_a ) __a = self.normalize(_a ).to(latents.dtype ) __a = self.clip_model.get_image_features(_a ) __a = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_a ) __a = spherical_dist_loss(_a , _a ).mean() * clip_guidance_scale __a = -torch.autograd.grad(_a , _a )[0] if isinstance(self.scheduler , _a ): __a = latents.detach() + grads * (sigma**2) __a = noise_pred_original else: __a = noise_pred_original - torch.sqrt(_a ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , _a , _a , _a = None , _a = None , _a = 512 , _a = 512 , _a = 0.6 , _a = 50 , _a = 7.5 , _a = 1 , _a = 0.0 , _a = 100 , _a = None , _a = "pil" , _a = True , _a = 0.8 , _a = 0.1 , _a = 0.1 , ): if isinstance(_a , _a ) and len(_a ) != batch_size: raise ValueError(f'''You have passed {batch_size} batch_size, but only {len(_a )} generators.''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if isinstance(_a , torch.Generator ) and batch_size > 1: __a = [generator] + [None] * (batch_size - 1) __a = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] __a = [x[0] for x in coca_is_none if x[1]] __a = ''', '''.join(_a ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(_a ): raise ValueError( f'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' f'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) __a = self.get_image_description(_a ) if style_prompt is None: if len(_a ): raise ValueError( f'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' f''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) __a = self.get_image_description(_a ) # get prompt text embeddings for content and style __a = self.tokenizer( _a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=_a , return_tensors='''pt''' , ) __a = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] __a = self.tokenizer( _a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=_a , return_tensors='''pt''' , ) __a = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] __a = slerp(_a , _a , _a ) # duplicate text embeddings for each generation per prompt __a = text_embeddings.repeat_interleave(_a , dim=0 ) # set timesteps __a = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) __a = {} if accepts_offset: __a = 1 self.scheduler.set_timesteps(_a , **_a ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) __a , __a = self.get_timesteps(_a , _a , self.device ) __a = timesteps[:1].repeat(_a ) # Preprocess image __a = preprocess(_a , _a , _a ) __a = self.prepare_latents( _a , _a , _a , text_embeddings.dtype , self.device , _a ) __a = preprocess(_a , _a , _a ) __a = self.prepare_latents( _a , _a , _a , text_embeddings.dtype , self.device , _a ) __a = slerp(_a , _a , _a ) if clip_guidance_scale > 0: __a = self.get_clip_image_embeddings(_a , _a ) __a = self.get_clip_image_embeddings(_a , _a ) __a = slerp( _a , _a , _a ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __a = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __a = content_text_input.input_ids.shape[-1] __a = self.tokenizer([''''''] , padding='''max_length''' , max_length=_a , return_tensors='''pt''' ) __a = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt __a = uncond_embeddings.repeat_interleave(_a , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __a = 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`. __a = (batch_size, self.unet.config.in_channels, height // 8, width // 8) __a = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps __a = torch.randn(_a , generator=_a , device='''cpu''' , dtype=_a ).to( self.device ) else: __a = torch.randn(_a , generator=_a , device=self.device , dtype=_a ) else: if latents.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) __a = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __a = 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] __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta # check if the scheduler accepts generator __a = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: __a = generator with self.progress_bar(total=_a ): for i, t in enumerate(_a ): # expand the latents if we are doing classifier free guidance __a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a , encoder_hidden_states=_a ).sample # perform classifier free guidance if do_classifier_free_guidance: __a , __a = noise_pred.chunk(2 ) __a = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: __a = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) __a , __a = self.cond_fn( _a , _a , _a , _a , _a , _a , _a , ) # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 1 / 0.1_8215 * latents __a = self.vae.decode(_a ).sample __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=_a , nsfw_content_detected=_a )
65
0
"""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
720
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowercase_ = abspath(join(dirname(dirname(dirname(__file__))), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def lowercase ( lowerCAmelCase__ : List[Any] ) -> str: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int ) -> Union[str, Any]: from transformers.testing_utils import pytest_terminal_summary_main __a = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(lowerCAmelCase__ , id=lowerCAmelCase__ )
65
0
"""simple docstring""" from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "huggingface/time-series-transformer-tourism-monthly": ( "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = 'time_series_transformer' __UpperCAmelCase : str = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self , _a = None , _a = None , _a = "student_t" , _a = "nll" , _a = 1 , _a = [1, 2, 3, 4, 5, 6, 7] , _a = "mean" , _a = 0 , _a = 0 , _a = 0 , _a = 0 , _a = None , _a = None , _a = 32 , _a = 32 , _a = 2 , _a = 2 , _a = 2 , _a = 2 , _a = True , _a = "gelu" , _a = 64 , _a = 0.1 , _a = 0.1 , _a = 0.1 , _a = 0.1 , _a = 0.1 , _a = 100 , _a = 0.02 , _a=True , **_a , ): # time series specific configuration __a = prediction_length __a = context_length or prediction_length __a = distribution_output __a = loss __a = input_size __a = num_time_features __a = lags_sequence __a = scaling __a = num_dynamic_real_features __a = num_static_real_features __a = num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(UpperCAmelCase__ ) != num_static_categorical_features: raise ValueError( '''The cardinality should be a list of the same length as `num_static_categorical_features`''' ) __a = cardinality else: __a = [0] if embedding_dimension and num_static_categorical_features > 0: if len(UpperCAmelCase__ ) != num_static_categorical_features: raise ValueError( '''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' ) __a = embedding_dimension else: __a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __a = num_parallel_samples # Transformer architecture configuration __a = input_size * len(UpperCAmelCase__ ) + self._number_of_features __a = d_model __a = encoder_attention_heads __a = decoder_attention_heads __a = encoder_ffn_dim __a = decoder_ffn_dim __a = encoder_layers __a = decoder_layers __a = dropout __a = attention_dropout __a = activation_dropout __a = encoder_layerdrop __a = decoder_layerdrop __a = activation_function __a = init_std __a = use_cache super().__init__(is_encoder_decoder=UpperCAmelCase__ , **UpperCAmelCase__ ) @property def __UpperCAmelCase ( self ): return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
721
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase_ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __UpperCAmelCase : Any = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __UpperCAmelCase : Any = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __UpperCAmelCase : Dict = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def __UpperCAmelCase ( self , _a , _a , _a ): __a = ZeroShotClassificationPipeline( model=_a , tokenizer=_a , candidate_labels=['''polics''', '''health'''] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def __UpperCAmelCase ( self , _a , _a ): __a = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics''' ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) # No kwarg __a = classifier('''Who are you voting for in 2020?''' , ['''politics'''] ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics'''] ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics, public health''' ) self.assertEqual( _a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health'''] ) self.assertEqual( _a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) __a = classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''This text is about {}''' ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) # https://github.com/huggingface/transformers/issues/13846 __a = classifier(['''I am happy'''] , ['''positive''', '''negative'''] ) self.assertEqual( _a , [ {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} for i in range(1 ) ] , ) __a = classifier(['''I am happy''', '''I am sad'''] , ['''positive''', '''negative'''] ) self.assertEqual( _a , [ {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} for i in range(2 ) ] , ) with self.assertRaises(_a ): classifier('''''' , candidate_labels='''politics''' ) with self.assertRaises(_a ): classifier(_a , candidate_labels='''politics''' ) with self.assertRaises(_a ): classifier('''Who are you voting for in 2020?''' , candidate_labels='''''' ) with self.assertRaises(_a ): classifier('''Who are you voting for in 2020?''' , candidate_labels=_a ) with self.assertRaises(_a ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''Not formatting template''' , ) with self.assertRaises(_a ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template=_a , ) self.run_entailment_id(_a ) def __UpperCAmelCase ( self , _a ): __a = zero_shot_classifier.model.config __a = config.labelaid __a = zero_shot_classifier.entailment_id __a = {'''LABEL_0''': 0, '''LABEL_1''': 1, '''LABEL_2''': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) __a = {'''entailment''': 0, '''neutral''': 1, '''contradiction''': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __a = {'''ENTAIL''': 0, '''NON-ENTAIL''': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __a = {'''ENTAIL''': 2, '''NEUTRAL''': 1, '''CONTR''': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) __a = original_labelaid self.assertEqual(_a , zero_shot_classifier.entailment_id ) @require_torch def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( '''Who are you voting for in 2020?''' * 100 , candidate_labels=['''politics''', '''public health''', '''science'''] ) @require_torch def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @require_tf def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''tf''' , ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @slow @require_torch def __UpperCAmelCase ( self ): __a = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''pt''' ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) __a = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=_a , ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , ) @slow @require_tf def __UpperCAmelCase ( self ): __a = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''tf''' ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) __a = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=_a , ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , )
65
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) lowercase_ = logging.getLogger(__name__) @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Dict = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) __UpperCAmelCase : str = field( default=__a , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) __UpperCAmelCase : Optional[Any] = field( default=__a , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) __UpperCAmelCase : Tuple = field( default=__a , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) __UpperCAmelCase : List[str] = field(default=__a , metadata={'help': 'Whether tp freeze the encoder.'} ) __UpperCAmelCase : Union[str, Any] = field(default=__a , metadata={'help': 'Whether to freeze the embeddings.'} ) @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[Any] = field( metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'} ) __UpperCAmelCase : Dict = field( default='summarization' , metadata={'help': 'Task name, summarization (or summarization_{dataset} for pegasus) or translation'} , ) __UpperCAmelCase : int = field( default=1_0_2_4 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __UpperCAmelCase : Optional[Any] = field( default=1_2_8 , metadata={ 'help': ( 'The maximum total sequence length for target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __UpperCAmelCase : List[Any] = field( default=1_4_2 , metadata={ 'help': ( 'The maximum total sequence length for validation target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded. ' 'This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ' 'during ``evaluate`` and ``predict``.' ) } , ) __UpperCAmelCase : Dict = field( default=1_4_2 , metadata={ 'help': ( 'The maximum total sequence length for test target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __UpperCAmelCase : str = field(default=-1 , metadata={'help': '# training examples. -1 means use all.'} ) __UpperCAmelCase : Dict = field(default=-1 , metadata={'help': '# validation examples. -1 means use all.'} ) __UpperCAmelCase : Optional[int] = field(default=-1 , metadata={'help': '# test examples. -1 means use all.'} ) __UpperCAmelCase : int = field(default=__a , metadata={'help': 'Source language id for translation.'} ) __UpperCAmelCase : Dict = field(default=__a , metadata={'help': 'Target language id for translation.'} ) __UpperCAmelCase : Optional[Any] = field(default=__a , metadata={'help': '# num_beams to use for evaluation.'} ) __UpperCAmelCase : Optional[int] = field( default=__a , metadata={'help': 'If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'} , ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] ) -> Optional[Any]: logger.info(f'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(f''' {key} = {metrics[key]}''' ) save_json(lowerCAmelCase__ , os.path.join(lowerCAmelCase__ , f'''{split}_results.json''' ) ) def lowercase ( ) -> str: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __a = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __a , __a , __a = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __a , __a , __a = parser.parse_args_into_dataclasses() check_output_dir(lowerCAmelCase__ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , lowerCAmelCase__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __a = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __a = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): assert hasattr(lowerCAmelCase__ , lowerCAmelCase__ ), f'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(lowerCAmelCase__ , lowerCAmelCase__ , getattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) __a = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __a = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=lowerCAmelCase__ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(lowerCAmelCase__ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: __a = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(lowerCAmelCase__ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = tokenizer.lang_code_to_id[data_args.tgt_lang] else: __a = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(lowerCAmelCase__ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) __a = SeqaSeqDataset # Get datasets __a = ( dataset_class( lowerCAmelCase__ , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) __a = ( dataset_class( lowerCAmelCase__ , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) __a = ( dataset_class( lowerCAmelCase__ , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer __a = ( build_compute_metrics_fn(data_args.task , lowerCAmelCase__ ) if training_args.predict_with_generate else None ) __a = SeqaSeqTrainer( model=lowerCAmelCase__ , args=lowerCAmelCase__ , data_args=lowerCAmelCase__ , train_dataset=lowerCAmelCase__ , eval_dataset=lowerCAmelCase__ , data_collator=SeqaSeqDataCollator( lowerCAmelCase__ , lowerCAmelCase__ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , ) __a = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) __a = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) __a = train_result.metrics __a = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , lowerCAmelCase__ , training_args.output_dir ) all_metrics.update(lowerCAmelCase__ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __a = trainer.evaluate(metric_key_prefix='''val''' ) __a = data_args.n_val __a = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , lowerCAmelCase__ , training_args.output_dir ) all_metrics.update(lowerCAmelCase__ ) if training_args.do_predict: logger.info('''*** Predict ***''' ) __a = trainer.predict(test_dataset=lowerCAmelCase__ , metric_key_prefix='''test''' ) __a = test_output.metrics __a = data_args.n_test if trainer.is_world_process_zero(): __a = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , lowerCAmelCase__ , training_args.output_dir ) all_metrics.update(lowerCAmelCase__ ) if training_args.predict_with_generate: __a = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ ) __a = lmap(str.strip , lowerCAmelCase__ ) write_txt_file(lowerCAmelCase__ , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(lowerCAmelCase__ , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def lowercase ( lowerCAmelCase__ : List[str] ) -> List[str]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
700
"""simple docstring""" import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowercase ( lowerCAmelCase__ : Optional[int] ) -> int: monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pytest.fixture def lowercase ( lowerCAmelCase__ : Any ) -> Any: class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): __a = metric_id class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Any = [MetricMock(__SCREAMING_SNAKE_CASE ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']] def __UpperCAmelCase ( self ): return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() ) @pytest.mark.parametrize( '''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple ) -> Optional[int]: if "tmp_path" in args: __a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(lowerCAmelCase__ , match='''https://huggingface.co/docs/evaluate''' ): func(*lowerCAmelCase__ )
65
0
"""simple docstring""" import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class __lowerCAmelCase ( unittest.TestCase , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = load_tool('''text-to-speech''' ) self.tool.setup() def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = self.tool('''hey''' ) __a = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.000_5966_6688_3211_5829, -0.000_3657_6401_9079_5064, -0.0001_3439_5027_9988_3485] ) , ) ) def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = self.tool('''hey''' ) __a = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.000_5966_6688_3211_5829, -0.000_3657_6401_9079_5064, -0.0001_3439_5027_9988_3485] ) , ) )
701
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> int: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or number < 0: raise ValueError('''Input must be a non-negative integer''' ) __a = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : Optional[Any] ) -> str: # preprocessing the first row for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(lowercase__ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(lowercase__ ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
702
"""simple docstring""" import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[Any] ) -> str: assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int ) -> Tuple: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( '''features''' , [ None, {'''text''': '''string'''}, {'''text''': '''int32'''}, {'''text''': '''float32'''}, ] , ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Union[str, Any] ) -> Optional[int]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) __a = TextDatasetReader(lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict ) -> Optional[Any]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , split=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any] ) -> Dict: if issubclass(lowerCAmelCase__ , lowerCAmelCase__ ): __a = text_path elif issubclass(lowerCAmelCase__ , lowerCAmelCase__ ): __a = [text_path] __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Union[str, Any]=("train",) ) -> Optional[Any]: assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) for split in splits: __a = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any] ) -> Union[str, Any]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a = TextDatasetReader({'''train''': text_path} , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( '''features''' , [ None, {'''text''': '''string'''}, {'''text''': '''int32'''}, {'''text''': '''float32'''}, ] , ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] ) -> str: __a = tmp_path / '''cache''' # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" __a = {'''text''': '''string'''} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) __a = TextDatasetReader({'''train''': text_path} , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple ) -> Dict: if split: __a = {split: text_path} else: __a = '''train''' __a = {'''train''': text_path, '''test''': text_path} __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() )
65
0
class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): __a = size __a = [0] * size __a = [0] * size @staticmethod def __UpperCAmelCase ( _a ): return index | (index + 1) @staticmethod def __UpperCAmelCase ( _a ): return (index & (index + 1)) - 1 def __UpperCAmelCase ( self , _a , _a ): __a = value while index < self.size: __a = self.get_prev(lowercase__ ) + 1 if current_left_border == index: __a = value else: __a = max(lowercase__ , lowercase__ , lowercase__ ) __a = self.get_next(lowercase__ ) def __UpperCAmelCase ( self , _a , _a ): right -= 1 # Because of right is exclusive __a = 0 while left <= right: __a = self.get_prev(lowercase__ ) if left <= current_left: __a = max(lowercase__ , self.tree[right] ) __a = current_left else: __a = max(lowercase__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
703
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class __lowerCAmelCase ( _UpperCAmelCase , unittest.TestCase ): '''simple docstring''' snake_case : int = CpmAntTokenizer snake_case : List[Any] = False def __UpperCAmelCase ( self ): super().setUp() __a = [ """<d>""", """</d>""", """<s>""", """</s>""", """</_>""", """<unk>""", """<pad>""", """</n>""", """我""", """是""", """C""", """P""", """M""", """A""", """n""", """t""", ] __a = 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] ) ) @tooslow def __UpperCAmelCase ( self ): __a = CpmAntTokenizer.from_pretrained('''openbmb/cpm-ant-10b''' ) __a = """今天天气真好!""" __a = ["""今天""", """天气""", """真""", """好""", """!"""] __a = tokenizer.tokenize(lowercase__ ) self.assertListEqual(lowercase__ , lowercase__ ) __a = """今天天气真好!""" __a = [tokenizer.bos_token] + tokens __a = [6, 9_802, 14_962, 2_082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase__ ) , lowercase__ ) __a = tokenizer.decode(lowercase__ ) self.assertEqual(lowercase__ , lowercase__ )
704
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir("fixtures/test_sentencepiece_bpe_char.model") @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = SpeechTaTokenizer __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = True def __UpperCAmelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing __a = SpeechTaTokenizer(_a ) __a = AddedToken('''<mask>''' , lstrip=_a , rstrip=_a ) __a = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self , _a ): __a = '''this is a test''' __a = '''this is a test''' return input_text, output_text def __UpperCAmelCase ( self , _a , _a=False , _a=20 , _a=5 ): __a , __a = self.get_input_output_texts(_a ) __a = tokenizer.encode(_a , add_special_tokens=_a ) __a = tokenizer.decode(_a , clean_up_tokenization_spaces=_a ) return text, ids def __UpperCAmelCase ( self ): __a = '''<pad>''' __a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def __UpperCAmelCase ( self ): __a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(_a ) , 81 ) def __UpperCAmelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __UpperCAmelCase ( self ): __a = self.get_tokenizers(do_lower_case=_a ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) __a = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] __a = tokenizer.add_tokens(_a ) __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) self.assertEqual(_a , _a ) self.assertEqual(_a , len(_a ) ) self.assertEqual(_a , all_size + len(_a ) ) __a = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=_a ) self.assertGreaterEqual(len(_a ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) __a = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} __a = tokenizer.add_special_tokens(_a ) __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) self.assertEqual(_a , _a ) self.assertEqual(_a , len(_a ) ) self.assertEqual(_a , all_size_a + len(_a ) ) __a = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=_a ) self.assertGreaterEqual(len(_a ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = self.get_tokenizer() __a = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(_a , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) __a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) __a = tokenizer.convert_tokens_to_ids(_a ) # fmt: off self.assertListEqual(_a , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on __a = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def __UpperCAmelCase ( self ): # Use custom sequence because this tokenizer does not handle numbers. __a = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off __a = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=_a , )
65
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = 'bert-generation' def __init__( self , _a=50_358 , _a=1_024 , _a=24 , _a=16 , _a=4_096 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=0.02 , _a=1E-12 , _a=0 , _a=2 , _a=1 , _a="absolute" , _a=True , **_a , ): super().__init__(pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , **__snake_case ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = initializer_range __a = layer_norm_eps __a = position_embedding_type __a = use_cache
705
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = ['input_features', 'attention_mask'] def __init__( self , _a=80 , _a=16_000 , _a=0.0 , _a=10 , _a=25 , _a="hamming_window" , _a=3_2768.0 , _a=0.97 , _a=1.0 , _a=True , _a=True , _a=False , **_a , ): super().__init__(feature_size=_a , sampling_rate=_a , padding_value=_a , **_a ) __a = feature_size __a = sampling_rate __a = padding_value __a = hop_length __a = win_length __a = frame_signal_scale __a = preemphasis_coeff __a = mel_floor __a = normalize_means __a = normalize_vars __a = win_function __a = return_attention_mask __a = win_length * sampling_rate // 1_000 __a = hop_length * sampling_rate // 1_000 __a = optimal_fft_length(self.sample_size ) __a = (self.n_fft // 2) + 1 def __UpperCAmelCase ( self , _a ): if self.win_function == "hamming_window": __a = window_function(window_length=self.sample_size , name=self.win_function , periodic=_a ) else: __a = window_function(window_length=self.sample_size , name=self.win_function ) __a = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) __a = spectrogram( one_waveform * self.frame_signal_scale , window=_a , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=_a , preemphasis=self.preemphasis_coeff , mel_filters=_a , mel_floor=self.mel_floor , log_mel='''log''' , ) return msfc_features.T def __UpperCAmelCase ( self , _a , _a , _a ): # make sure we normalize float32 arrays if self.normalize_means: __a = x[:input_length].mean(axis=0 ) __a = np.subtract(_a , _a ) if self.normalize_vars: __a = x[:input_length].std(axis=0 ) __a = np.divide(_a , _a ) if input_length < x.shape[0]: __a = padding_value # make sure array is in float32 __a = x.astype(np.floataa ) return x def __UpperCAmelCase ( self , _a , _a = None ): __a = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(_a , _a , self.padding_value ) for x, n in zip(_a , _a )] def __call__( self , _a , _a = False , _a = None , _a = False , _a = None , _a = None , _a = None , _a = None , **_a , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with''' f''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __a = isinstance(_a , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) __a = is_batched_numpy or ( isinstance(_a , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __a = [np.asarray(_a , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_a , np.ndarray ): __a = np.asarray(_a , dtype=np.floataa ) elif isinstance(_a , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __a = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __a = [raw_speech] # extract fbank features __a = [self._extract_mfsc_features(_a ) for one_waveform in raw_speech] # convert into correct format for padding __a = BatchFeature({'''input_features''': features} ) __a = self.pad( _a , padding=_a , max_length=_a , truncation=_a , pad_to_multiple_of=_a , return_attention_mask=_a , **_a , ) # make sure list is in array format __a = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , _a ): __a = [np.asarray(_a , dtype=np.floataa ) for feature in input_features] __a = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __a = [np.asarray(_a , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: __a = ( np.array(_a , dtype=np.intaa ) if self._get_padding_strategies(_a , max_length=_a ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) __a = self.normalize( padded_inputs['''input_features'''] , attention_mask=_a ) if return_tensors is not None: __a = padded_inputs.convert_to_tensors(_a ) return padded_inputs
65
0
import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @property def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def __UpperCAmelCase ( self ): __a = self.dummy_uncond_unet __a = PNDMScheduler() __a = PNDMPipeline(unet=_a , scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) __a = torch.manual_seed(0 ) __a = pndm(generator=_a , num_inference_steps=20 , output_type='''numpy''' ).images __a = torch.manual_seed(0 ) __a = pndm(generator=_a , num_inference_steps=20 , output_type='''numpy''' , return_dict=_a )[0] __a = image[0, -3:, -3:, -1] __a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __a = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = '''google/ddpm-cifar10-32''' __a = UNetaDModel.from_pretrained(_a ) __a = PNDMScheduler() __a = PNDMPipeline(unet=_a , scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) __a = torch.manual_seed(0 ) __a = pndm(generator=_a , output_type='''numpy''' ).images __a = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __a = np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
706
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env' ) @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue_model_parallelism.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_6_0_0, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_6_0_0, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, ] ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=_a , ) assert hasattr(self , '''env''' ) def __UpperCAmelCase ( self , _a ): # configuration for running training on smdistributed Model Parallel __a = { '''enabled''': True, '''processes_per_host''': 8, } __a = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __a = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __a = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=_a , instance_type=self.instance_type , debugger_hook_config=_a , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 500, } , metric_definitions=self.env.metric_definitions , distribution=_a , py_version='''py36''' , ) def __UpperCAmelCase ( self , _a ): TrainingJobAnalytics(_a ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __UpperCAmelCase ( self , _a ): # create estimator __a = self.create_estimator(_a ) # run training estimator.fit() # result dataframe __a = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __a = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 999_999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , _a )
65
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> str: if not all(char in '''01''' for char in bin_string ): raise ValueError('''Non-binary value was passed to the function''' ) if not bin_string: raise ValueError('''Empty string was passed to the function''' ) __a = "" while len(lowercase_ ) % 3 != 0: __a = "0" + bin_string __a = [ bin_string[index : index + 3] for index in range(len(lowercase_ ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: __a = 0 for index, val in enumerate(lowercase_ ): oct_val += int(2 ** (2 - index) * int(lowercase_ ) ) oct_string += str(lowercase_ ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
707
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
65
0
"""simple docstring""" import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( UpperCAmelCase_ ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = (UnCLIPScheduler,) def __UpperCAmelCase ( self , **_a ): __a = { '''num_train_timesteps''': 1_000, '''variance_type''': '''fixed_small_log''', '''clip_sample''': True, '''clip_sample_range''': 1.0, '''prediction_type''': '''epsilon''', } config.update(**_snake_case ) return config def __UpperCAmelCase ( self ): for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_snake_case ) def __UpperCAmelCase ( self ): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=_snake_case ) def __UpperCAmelCase ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=_snake_case ) def __UpperCAmelCase ( self ): for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=_snake_case ) def __UpperCAmelCase ( self ): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=_snake_case ) def __UpperCAmelCase ( self ): for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=_snake_case , prev_timestep=_snake_case ) def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(variance_type='''fixed_small_log''' ) __a = scheduler_class(**_snake_case ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0_000E-10 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.054_9625 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.999_4987 ) ) < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(variance_type='''learned_range''' ) __a = scheduler_class(**_snake_case ) __a = 0.5 assert scheduler._get_variance(1 , predicted_variance=_snake_case ) - -10.171_2790 < 1E-5 assert scheduler._get_variance(487 , predicted_variance=_snake_case ) - -5.799_8052 < 1E-5 assert scheduler._get_variance(999 , predicted_variance=_snake_case ) - -0.001_0011 < 1E-5 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = scheduler.timesteps __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for i, t in enumerate(_snake_case ): # 1. predict noise residual __a = model(_snake_case , _snake_case ) # 2. predict previous mean of sample x_t-1 __a = scheduler.step(_snake_case , _snake_case , _snake_case , generator=_snake_case ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_snake_case ) ) __a = torch.mean(torch.abs(_snake_case ) ) assert abs(result_sum.item() - 252.268_2495 ) < 1E-2 assert abs(result_mean.item() - 0.328_4743 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) scheduler.set_timesteps(25 ) __a = scheduler.timesteps __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for i, t in enumerate(_snake_case ): # 1. predict noise residual __a = model(_snake_case , _snake_case ) if i + 1 == timesteps.shape[0]: __a = None else: __a = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __a = scheduler.step( _snake_case , _snake_case , _snake_case , prev_timestep=_snake_case , generator=_snake_case ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_snake_case ) ) __a = torch.mean(torch.abs(_snake_case ) ) assert abs(result_sum.item() - 258.204_4983 ) < 1E-2 assert abs(result_mean.item() - 0.336_2038 ) < 1E-3 def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass
708
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable lowercase_ = {"configuration_gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["GPTNeoXTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXForCausalLM", "GPTNeoXForQuestionAnswering", "GPTNeoXForSequenceClassification", "GPTNeoXForTokenClassification", "GPTNeoXLayer", "GPTNeoXModel", "GPTNeoXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
65
0
"""simple docstring""" lowercase_ = { """a""": """AAAAA""", """b""": """AAAAB""", """c""": """AAABA""", """d""": """AAABB""", """e""": """AABAA""", """f""": """AABAB""", """g""": """AABBA""", """h""": """AABBB""", """i""": """ABAAA""", """j""": """BBBAA""", """k""": """ABAAB""", """l""": """ABABA""", """m""": """ABABB""", """n""": """ABBAA""", """o""": """ABBAB""", """p""": """ABBBA""", """q""": """ABBBB""", """r""": """BAAAA""", """s""": """BAAAB""", """t""": """BAABA""", """u""": """BAABB""", """v""": """BBBAB""", """w""": """BABAA""", """x""": """BABAB""", """y""": """BABBA""", """z""": """BABBB""", """ """: """ """, } lowercase_ = {value: key for key, value in encode_dict.items()} def lowercase ( lowerCAmelCase__ : Optional[int] ) -> Union[str, Any]: __a = '''''' for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception('''encode() accepts only letters of the alphabet and spaces''' ) return encoded def lowercase ( lowerCAmelCase__ : Optional[Any] ) -> str: if set(lowerCAmelCase__ ) - {"A", "B", " "} != set(): raise Exception('''decode() accepts only \'A\', \'B\' and spaces''' ) __a = '''''' for word in coded.split(): while len(lowerCAmelCase__ ) != 0: decoded += decode_dict[word[:5]] __a = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
709
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=2 , _a=8 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=16 , _a=5 , _a=2 , _a=36 , _a="gelu" , _a=0.0 , _a=0.0 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self ): __a = self.get_config() __a = 300 return config def __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraModel(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a ) __a = model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = MraModel(_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , ) __a = model( _a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , ) __a = model(_a , attention_mask=_a , token_type_ids=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraForMaskedLM(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraForQuestionAnswering(config=_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , token_type_ids=_a , start_positions=_a , end_positions=_a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MraForSequenceClassification(_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MraForTokenClassification(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_choices __a = MraForMultipleChoice(config=_a ) model.to(_a ) model.eval() __a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) __UpperCAmelCase : str = False __UpperCAmelCase : Any = False __UpperCAmelCase : List[Any] = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Dict = () def __UpperCAmelCase ( self ): __a = MraModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a = type self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MraModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip(reason='''MRA does not output attentions''' ) def __UpperCAmelCase ( self ): return @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = MraModel.from_pretrained('''uw-madison/mra-base-512-4''' ) __a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4''' ) __a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = 50_265 __a = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3''' ) __a = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = 50_265 __a = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
65
0
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class __lowerCAmelCase ( UpperCamelCase__ ): '''simple docstring''' __UpperCAmelCase : Any = field(default='summarization' , metadata={'include_in_asdict_even_if_is_default': True} ) __UpperCAmelCase : List[Any] = Features({'text': Value('string' )} ) __UpperCAmelCase : Optional[int] = Features({'summary': Value('string' )} ) __UpperCAmelCase : Dict = 'text' __UpperCAmelCase : List[Any] = 'summary' @property def __UpperCAmelCase ( self ): return {self.text_column: "text", self.summary_column: "summary"}
710
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> list[str]: if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number_of_bytes!''' ) __a = number_of_bytes // partitions __a = [] for i in range(lowerCAmelCase__ ): __a = i * bytes_per_partition + 1 __a = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = JukeboxTokenizer __UpperCAmelCase : Optional[int] = { 'artist': 'Zac Brown Band', 'genres': 'Country', 'lyrics': 'I met a traveller from an antique land,\n Who said \"Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ', } @require_torch def __UpperCAmelCase ( self ): import torch __a = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) __a = tokenizer(**self.metas )['''input_ids'''] # fmt: off __a = [ torch.tensor([[ 0, 0, 0, 7_169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1_069, 11]] ), torch.tensor([[0, 0, 0, 1_069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def __UpperCAmelCase ( self ): import torch __a = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) __a = tokenizer(**self.metas )['''input_ids'''] # fmt: off __a = [ torch.tensor([[ 0, 0, 0, 1_069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
711
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> list: __a = len(lowerCAmelCase__ ) __a = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): __a = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> Dict: return int(input_a == input_a == 0 ) def lowercase ( ) -> Union[str, Any]: print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(f'''| 0 | 0 | {nor_gate(0 , 0 )} |''' ) print(f'''| 0 | 1 | {nor_gate(0 , 1 )} |''' ) print(f'''| 1 | 0 | {nor_gate(1 , 0 )} |''' ) print(f'''| 1 | 1 | {nor_gate(1 , 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
712
"""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 lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} lowercase_ = { "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" ), }, } lowercase_ = { "allenai/longformer-base-4096": 4_0_9_6, "allenai/longformer-large-4096": 4_0_9_6, "allenai/longformer-large-4096-finetuned-triviaqa": 4_0_9_6, "allenai/longformer-base-4096-extra.pos.embd.only": 4_0_9_6, "allenai/longformer-large-4096-extra.pos.embd.only": 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowercase ( ) -> Union[str, Any]: __a = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __a = bs[:] __a = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCAmelCase__ ) cs.append(2**8 + n ) n += 1 __a = [chr(lowerCAmelCase__ ) for n in cs] return dict(zip(lowerCAmelCase__ , lowerCAmelCase__ ) ) def lowercase ( lowerCAmelCase__ : Tuple ) -> Tuple: __a = set() __a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __a = char return pairs class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = VOCAB_FILES_NAMES __UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Union[str, Any] = ['input_ids', 'attention_mask'] def __init__( self , _a , _a , _a="replace" , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=False , **_a , ): __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else bos_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else sep_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else cls_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( errors=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , **_a , ) with open(_a , encoding='''utf-8''' ) as vocab_handle: __a = json.load(_a ) __a = {v: k for k, v in self.encoder.items()} __a = errors # how to handle errors in decoding __a = bytes_to_unicode() __a = {v: k for k, v in self.byte_encoder.items()} with open(_a , encoding='''utf-8''' ) as merges_handle: __a = merges_handle.read().split('''\n''' )[1:-1] __a = [tuple(merge.split() ) for merge in bpe_merges] __a = dict(zip(_a , range(len(_a ) ) ) ) __a = {} __a = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __a = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def __UpperCAmelCase ( self ): return len(self.encoder ) def __UpperCAmelCase ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def __UpperCAmelCase ( self , _a ): if token in self.cache: return self.cache[token] __a = tuple(_a ) __a = get_pairs(_a ) if not pairs: return token while True: __a = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __a , __a = bigram __a = [] __a = 0 while i < len(_a ): try: __a = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __a = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __a = tuple(_a ) __a = new_word if len(_a ) == 1: break else: __a = get_pairs(_a ) __a = ''' '''.join(_a ) __a = word return word def __UpperCAmelCase ( self , _a ): __a = [] for token in re.findall(self.pat , _a ): __a = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(''' ''' ) ) return bpe_tokens def __UpperCAmelCase ( self , _a ): return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def __UpperCAmelCase ( self , _a ): return self.decoder.get(_a ) def __UpperCAmelCase ( self , _a ): __a = ''''''.join(_a ) __a = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def __UpperCAmelCase ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_a , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '''\n''' ) __a = 0 with open(_a , '''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 _a : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __a = token_index writer.write(''' '''.join(_a ) + '''\n''' ) index += 1 return vocab_file, merge_file def __UpperCAmelCase ( self , _a , _a = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __a = [self.cls_token_id] __a = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __UpperCAmelCase ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self , _a , _a=False , **_a ): __a = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): __a = ''' ''' + text return (text, kwargs)
65
0
"""simple docstring""" import math class __lowerCAmelCase : '''simple docstring''' def __UpperCAmelCase ( self , _a , _a ): __a = 0.0 __a = 0.0 for i in range(len(_a ) ): 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 , _a , _a , _a , _a ): for i in range(len(_a ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def lowercase ( ) -> None: __a = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) __a = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training __a = SelfOrganizingMap() __a = 3 __a = 0.5 for _ in range(__snake_case ): for j in range(len(__snake_case ) ): # training sample __a = training_samples[j] # Compute the winning vector __a = self_organizing_map.get_winner(__snake_case , __snake_case ) # Update the winning vector __a = self_organizing_map.update(__snake_case , __snake_case , __snake_case , __snake_case ) # classify test sample __a = [0, 0, 0, 1] __a = self_organizing_map.get_winner(__snake_case , __snake_case ) # 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()
713
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "unc-nlp/lxmert-base-uncased": "https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = 'lxmert' __UpperCAmelCase : str = {} def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=9_500 , _a=1_600 , _a=400 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=9 , _a=5 , _a=5 , _a=2_048 , _a=4 , _a=6.67 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=True , _a=True , **_a , ): __a = vocab_size __a = hidden_size __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = num_qa_labels __a = num_object_labels __a = num_attr_labels __a = l_layers __a = x_layers __a = r_layers __a = visual_feat_dim __a = visual_pos_dim __a = visual_loss_normalizer __a = task_matched __a = task_mask_lm __a = task_obj_predict __a = task_qa __a = visual_obj_loss __a = visual_attr_loss __a = visual_feat_loss __a = {'''vision''': r_layers, '''cross_encoder''': x_layers, '''language''': l_layers} super().__init__(**_a )
65
0
"""simple docstring""" from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets lowercase_ = "\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n" lowercase_ = "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n" lowercase_ = "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n predictions: list of predictions to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"pearson\": Pearson Correlation\n \"spearmanr\": Spearman Correlation\n \"matthews_correlation\": Matthew Correlation\nExamples:\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'sst2\') # \'sst2\' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'mrpc\') # \'mrpc\' or \'qqp\'\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'stsb\')\n >>> references = [0., 1., 2., 3., 4., 5.]\n >>> predictions = [0., 1., 2., 3., 4., 5.]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n {\'pearson\': 1.0, \'spearmanr\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'cola\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n" def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict ) -> str: return float((preds == labels).mean() ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : int ) -> Union[str, Any]: __a = simple_accuracy(a__ , a__ ) __a = float(fa_score(y_true=a__ , y_pred=a__ ) ) return { "accuracy": acc, "f1": fa, } def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] ) -> Union[str, Any]: __a = float(pearsonr(a__ , a__ )[0] ) __a = float(spearmanr(a__ , a__ )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def __UpperCAmelCase ( self ): if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), '''references''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), } ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' , ) def __UpperCAmelCase ( self , _a , _a ): if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(__A , __A )} elif self.config_name == "stsb": return pearson_and_spearman(__A , __A ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(__A , __A ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(__A , __A )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' )
714
"""simple docstring""" import itertools import math def lowercase ( lowerCAmelCase__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( ) -> int: __a = 2 while True: if is_prime(lowerCAmelCase__ ): yield num num += 1 def lowercase ( lowerCAmelCase__ : int = 10001 ) -> int: return next(itertools.islice(prime_generator() , nth - 1 , lowerCAmelCase__ ) ) if __name__ == "__main__": print(F'''{solution() = }''')
65
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowercase_ = {"configuration_deit": ["DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DeiTConfig", "DeiTOnnxConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["DeiTFeatureExtractor"] lowercase_ = ["DeiTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "DEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "DeiTForImageClassification", "DeiTForImageClassificationWithTeacher", "DeiTForMaskedImageModeling", "DeiTModel", "DeiTPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDeiTForImageClassification", "TFDeiTForImageClassificationWithTeacher", "TFDeiTForMaskedImageModeling", "TFDeiTModel", "TFDeiTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
715
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase_ = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
65
0
"""simple docstring""" from math import pi def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[int] ) -> List[Any]: return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(9_0, 1_0))
716
"""simple docstring""" from sklearn.metrics import fa_score import datasets lowercase_ = "\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n" lowercase_ = "\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {'f1': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results['f1'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results['f1'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n >>> print(round(results['f1'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'f1': array([0.8, 0. , 0. ])}\n" lowercase_ = "\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def __UpperCAmelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'''] , ) def __UpperCAmelCase ( self , _a , _a , _a=None , _a=1 , _a="binary" , _a=None ): __a = fa_score( _a , _a , labels=_a , pos_label=_a , average=_a , sample_weight=_a ) return {"f1": float(_a ) if score.size == 1 else score}
65
0
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( UpperCamelCase_ ): '''simple docstring''' __UpperCAmelCase : List[Any] = (DEISMultistepScheduler,) __UpperCAmelCase : int = (('num_inference_steps', 2_5),) def __UpperCAmelCase ( self , **_a ): __a = { 'num_train_timesteps': 1_000, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, } config.update(**__a ) return config def __UpperCAmelCase ( self , _a=0 , **_a ): __a = dict(self.forward_default_kwargs ) __a = kwargs.pop('''num_inference_steps''' , __a ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config(**__a ) __a = scheduler_class(**__a ) scheduler.set_timesteps(__a ) # copy over dummy past residuals __a = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__a ) __a = scheduler_class.from_pretrained(__a ) new_scheduler.set_timesteps(__a ) # copy over dummy past residuals __a = dummy_past_residuals[: new_scheduler.config.solver_order] __a = sample, sample for t in range(__a , time_step + scheduler.config.solver_order + 1 ): __a = scheduler.step(__a , __a , __a , **__a ).prev_sample __a = new_scheduler.step(__a , __a , __a , **__a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self , _a=0 , **_a ): __a = dict(self.forward_default_kwargs ) __a = kwargs.pop('''num_inference_steps''' , __a ) __a = self.dummy_sample __a = 0.1 * sample __a = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__a ) scheduler.set_timesteps(__a ) # copy over dummy past residuals (must be after setting timesteps) __a = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__a ) __a = scheduler_class.from_pretrained(__a ) # copy over dummy past residuals new_scheduler.set_timesteps(__a ) # copy over dummy past residual (must be after setting timesteps) __a = dummy_past_residuals[: new_scheduler.config.solver_order] __a = scheduler.step(__a , __a , __a , **__a ).prev_sample __a = new_scheduler.step(__a , __a , __a , **__a ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def __UpperCAmelCase ( self , _a=None , **_a ): if scheduler is None: __a = self.scheduler_classes[0] __a = self.get_scheduler_config(**__a ) __a = scheduler_class(**__a ) __a = self.scheduler_classes[0] __a = self.get_scheduler_config(**__a ) __a = scheduler_class(**__a ) __a = 10 __a = self.dummy_model() __a = self.dummy_sample_deter scheduler.set_timesteps(__a ) for i, t in enumerate(scheduler.timesteps ): __a = model(__a , __a ) __a = scheduler.step(__a , __a , __a ).prev_sample return sample def __UpperCAmelCase ( self ): __a = dict(self.forward_default_kwargs ) __a = kwargs.pop('''num_inference_steps''' , __a ) for scheduler_class in self.scheduler_classes: __a = self.get_scheduler_config() __a = scheduler_class(**__a ) __a = self.dummy_sample __a = 0.1 * sample if num_inference_steps is not None and hasattr(__a , '''set_timesteps''' ): scheduler.set_timesteps(__a ) elif num_inference_steps is not None and not hasattr(__a , '''set_timesteps''' ): __a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __a = [residual + 0.2, residual + 0.15, residual + 0.10] __a = dummy_past_residuals[: scheduler.config.solver_order] __a = scheduler.timesteps[5] __a = scheduler.timesteps[6] __a = scheduler.step(__a , __a , __a , **__a ).prev_sample __a = scheduler.step(__a , __a , __a , **__a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __UpperCAmelCase ( self ): __a = DEISMultistepScheduler(**self.get_scheduler_config() ) __a = self.full_loop(scheduler=__a ) __a = torch.mean(torch.abs(__a ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1E-3 __a = DPMSolverSinglestepScheduler.from_config(scheduler.config ) __a = DPMSolverMultistepScheduler.from_config(scheduler.config ) __a = UniPCMultistepScheduler.from_config(scheduler.config ) __a = DEISMultistepScheduler.from_config(scheduler.config ) __a = self.full_loop(scheduler=__a ) __a = torch.mean(torch.abs(__a ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1E-3 def __UpperCAmelCase ( self ): for timesteps in [25, 50, 100, 999, 1_000]: self.check_over_configs(num_train_timesteps=__a ) def __UpperCAmelCase ( self ): self.check_over_configs(thresholding=__a ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=__a , prediction_type=__a , sample_max_value=__a , algorithm_type='''deis''' , solver_order=__a , solver_type=__a , ) def __UpperCAmelCase ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def __UpperCAmelCase ( self ): for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=__a , solver_type=__a , prediction_type=__a , algorithm_type=__a , ) __a = self.full_loop( solver_order=__a , solver_type=__a , prediction_type=__a , algorithm_type=__a , ) assert not torch.isnan(__a ).any(), "Samples have nan numbers" def __UpperCAmelCase ( self ): self.check_over_configs(lower_order_final=__a ) self.check_over_configs(lower_order_final=__a ) def __UpperCAmelCase ( self ): for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1_000]: self.check_over_forward(num_inference_steps=__a , time_step=0 ) def __UpperCAmelCase ( self ): __a = self.full_loop() __a = torch.mean(torch.abs(__a ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.full_loop(prediction_type='''v_prediction''' ) __a = torch.mean(torch.abs(__a ) ) assert abs(result_mean.item() - 0.091 ) < 1E-3 def __UpperCAmelCase ( self ): __a = self.scheduler_classes[0] __a = self.get_scheduler_config(thresholding=__a , dynamic_thresholding_ratio=0 ) __a = scheduler_class(**__a ) __a = 10 __a = self.dummy_model() __a = self.dummy_sample_deter.half() scheduler.set_timesteps(__a ) for i, t in enumerate(scheduler.timesteps ): __a = model(__a , __a ) __a = scheduler.step(__a , __a , __a ).prev_sample assert sample.dtype == torch.floataa
717
"""simple docstring""" from ..utils import DummyObject, requires_backends class __lowerCAmelCase ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = ['onnx'] def __init__( self , *_a , **_a ): requires_backends(self , ['''onnx'''] ) @classmethod def __UpperCAmelCase ( cls , *_a , **_a ): requires_backends(cls , ['''onnx'''] ) @classmethod def __UpperCAmelCase ( cls , *_a , **_a ): requires_backends(cls , ['''onnx'''] )
65
0
"""simple docstring""" import itertools import string from collections.abc import Generator, Iterable def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : int ) -> Optional[Any]: __a = iter(_lowercase ) while True: __a = tuple(itertools.islice(_lowercase , _lowercase ) ) if not chunk: return yield chunk def lowercase ( lowerCAmelCase__ : Dict ) -> Dict: __a = ''''''.join([c.upper() for c in dirty if c in string.ascii_letters] ) __a = '''''' if len(_lowercase ) < 2: return dirty for i in range(len(_lowercase ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(_lowercase ) & 1: clean += "X" return clean def lowercase ( lowerCAmelCase__ : Optional[int] ) -> Any: __a = '''ABCDEFGHIKLMNOPQRSTUVWXYZ''' # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler __a = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(_lowercase ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(_lowercase ) return table def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str] ) -> Tuple: __a = generate_table(_lowercase ) __a = prepare_input(_lowercase ) __a = '''''' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(_lowercase , 2 ): __a , __a = divmod(table.index(_lowercase ) , 5 ) __a , __a = divmod(table.index(_lowercase ) , 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Dict ) -> Dict: __a = generate_table(_lowercase ) __a = '''''' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(_lowercase , 2 ): __a , __a = divmod(table.index(_lowercase ) , 5 ) __a , __a = divmod(table.index(_lowercase ) , 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
718
"""simple docstring""" import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin lowercase_ = 1e-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=16 , _a=13 , _a=7 , _a=14 , _a=10 , _a=19 , _a=5 , _a=4 , _a=True , _a=16 , _a=2 , _a=4 , _a=4 , _a="gelu" , _a=0.1 , _a=0.1 , _a=[1, 2, 3, 4, 5] , _a=25 , _a=5 , ): __a = d_model __a = parent __a = batch_size __a = prediction_length __a = context_length __a = cardinality __a = num_time_features __a = lags_sequence __a = embedding_dimension __a = is_training __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = context_length __a = prediction_length + label_length __a = label_length __a = moving_average __a = autocorrelation_factor def __UpperCAmelCase ( self ): return AutoformerConfig( d_model=self.d_model , 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 , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def __UpperCAmelCase ( self , _a ): __a = config.context_length + max(config.lags_sequence ) __a = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) __a = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) __a = floats_tensor([self.batch_size, _past_length] ) __a = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs __a = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) __a = floats_tensor([self.batch_size, config.prediction_length] ) __a = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def __UpperCAmelCase ( self ): __a = self.get_config() __a = self.prepare_autoformer_inputs_dict(_a ) return config, inputs_dict def __UpperCAmelCase ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def __UpperCAmelCase ( self , _a , _a ): __a = AutoformerModel(config=_a ).to(_a ).eval() __a = model(**_a ) __a = outputs.encoder_last_hidden_state __a = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: __a = model.get_encoder() encoder.save_pretrained(_a ) __a = AutoformerEncoder.from_pretrained(_a ).to(_a ) __a , __a , __a , __a , __a = model.create_network_inputs(**_a ) __a , __a = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) __a = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) __a = encoder(inputs_embeds=_a )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) __a = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) __a = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) __a = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) __a = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: __a = model.get_decoder() decoder.save_pretrained(_a ) __a = AutoformerDecoder.from_pretrained(_a ).to(_a ) __a = decoder( trend=_a , inputs_embeds=_a , encoder_hidden_states=_a , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Any = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () __UpperCAmelCase : int = (AutoformerForPrediction,) if is_torch_available() else () __UpperCAmelCase : Any = {'feature-extraction': AutoformerModel} if is_torch_available() else {} __UpperCAmelCase : int = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : int = False __UpperCAmelCase : Any = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : int = False def __UpperCAmelCase ( self ): __a = AutoformerModelTester(self ) __a = ConfigTester(self , config_class=_a , has_text_modality=_a ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: __a = model_class(_a ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_a ) __a , __a = model_class.from_pretrained(_a , output_loading_info=_a ) self.assertEqual(info['''missing_keys'''] , [] ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*_a ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = inspect.signature(getattr(_a , '''forward''' ) ) # The main input is the name of the argument after `self` __a = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''' ) expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ] ) self.assertListEqual(arg_names[: len(_a )] , _a ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True __a = getattr(self.model_tester , '''seq_length''' , _a ) __a = getattr(self.model_tester , '''decoder_seq_length''' , _a ) __a = getattr(self.model_tester , '''encoder_seq_length''' , _a ) __a = getattr(self.model_tester , '''d_model''' , _a ) __a = getattr(self.model_tester , '''num_attention_heads''' , _a ) __a = d_model // num_attention_heads for model_class in self.all_model_classes: __a = True __a = False __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) __a = outputs.encoder_attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) __a = len(_a ) __a = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(_a , _a ) # decoder attentions __a = outputs.decoder_attentions self.assertIsInstance(_a , (list, tuple) ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions __a = outputs.cross_attentions self.assertIsInstance(_a , (list, tuple) ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine __a = True __a = True __a = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + 2 , len(_a ) ) __a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def __UpperCAmelCase ( self ): super().test_retain_grad_hidden_states_attentions() def lowercase ( lowerCAmelCase__ : Optional[int]="train-batch.pt" ) -> List[str]: __a = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=lowerCAmelCase__ , repo_type='''dataset''' ) __a = torch.load(lowerCAmelCase__ , map_location=lowerCAmelCase__ ) return batch @require_torch @slow class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch() with torch.no_grad(): __a = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] __a = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=_a ) self.assertTrue(torch.allclose(output[0, :3, :3] , _a , atol=_a ) ) def __UpperCAmelCase ( self ): __a = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): __a = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state __a = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=_a ) self.assertTrue(torch.allclose(output[0, :3, :3] , _a , atol=_a ) ) def __UpperCAmelCase ( self ): __a = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(_a ) __a = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): __a = model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) __a = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , _a ) __a = torch.tensor([3130.6763, 4056.5293, 7053.0786] , device=_a ) __a = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , _a , rtol=1E-1 ) )
65
0
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowerCAmelCase ( __snake_case , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Tuple = LDMTextToImagePipeline __UpperCAmelCase : Union[str, Any] = TEXT_TO_IMAGE_PARAMS - { 'negative_prompt', 'negative_prompt_embeds', 'cross_attention_kwargs', 'prompt_embeds', } __UpperCAmelCase : Dict = PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'callback', 'callback_steps', } __UpperCAmelCase : Dict = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase : Any = False def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = 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 , ) __a = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=_lowercase , set_alpha_to_one=_lowercase , ) torch.manual_seed(0 ) __a = AutoencoderKL( block_out_channels=(32, 64) , in_channels=3 , out_channels=3 , down_block_types=('''DownEncoderBlock2D''', '''DownEncoderBlock2D''') , up_block_types=('''UpDecoderBlock2D''', '''UpDecoderBlock2D''') , latent_channels=4 , ) torch.manual_seed(0 ) __a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) __a = CLIPTextModel(_lowercase ) __a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) __a = { """unet""": unet, """scheduler""": scheduler, """vqvae""": vae, """bert""": text_encoder, """tokenizer""": tokenizer, } return components def __UpperCAmelCase ( self , _a , _a=0 ): if str(_lowercase ).startswith('''mps''' ): __a = torch.manual_seed(_lowercase ) else: __a = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) __a = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __UpperCAmelCase ( self ): __a = """cpu""" # ensure determinism for the device-dependent torch.Generator __a = self.get_dummy_components() __a = LDMTextToImagePipeline(**_lowercase ) pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __a = self.get_dummy_inputs(_lowercase ) __a = pipe(**_lowercase ).images __a = image[0, -3:, -3:, -1] assert image.shape == (1, 16, 16, 3) __a = np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self , _a , _a=torch.floataa , _a=0 ): __a = torch.manual_seed(_lowercase ) __a = np.random.RandomState(_lowercase ).standard_normal((1, 4, 32, 32) ) __a = torch.from_numpy(_lowercase ).to(device=_lowercase , dtype=_lowercase ) __a = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __UpperCAmelCase ( self ): __a = LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256''' ).to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __a = self.get_inputs(_lowercase ) __a = pipe(**_lowercase ).images __a = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 256, 256, 3) __a = np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878] ) __a = np.abs(expected_slice - image_slice ).max() assert max_diff < 1E-3 @nightly @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self , _a , _a=torch.floataa , _a=0 ): __a = torch.manual_seed(_lowercase ) __a = np.random.RandomState(_lowercase ).standard_normal((1, 4, 32, 32) ) __a = torch.from_numpy(_lowercase ).to(device=_lowercase , dtype=_lowercase ) __a = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 50, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def __UpperCAmelCase ( self ): __a = LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256''' ).to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __a = self.get_inputs(_lowercase ) __a = pipe(**_lowercase ).images[0] __a = load_numpy( '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy''' ) __a = np.abs(expected_image - image ).max() assert max_diff < 1E-3
719
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str] ) -> Any: if isinstance(lowerCAmelCase__ , torch.Tensor ): return image elif isinstance(lowerCAmelCase__ , PIL.Image.Image ): __a = [image] if isinstance(image[0] , PIL.Image.Image ): __a = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] __a = np.concatenate(lowerCAmelCase__ , axis=0 ) __a = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 2_55.0 __a = image.transpose(0 , 3 , 1 , 2 ) __a = 2.0 * image - 1.0 __a = torch.from_numpy(lowerCAmelCase__ ) elif isinstance(image[0] , torch.Tensor ): __a = torch.cat(lowerCAmelCase__ , dim=0 ) return image def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[int]=0.99_95 ) -> int: if not isinstance(lowerCAmelCase__ , np.ndarray ): __a = True __a = va.device __a = va.cpu().numpy() __a = va.cpu().numpy() __a = np.sum(va * va / (np.linalg.norm(lowerCAmelCase__ ) * np.linalg.norm(lowerCAmelCase__ )) ) if np.abs(lowerCAmelCase__ ) > DOT_THRESHOLD: __a = (1 - t) * va + t * va else: __a = np.arccos(lowerCAmelCase__ ) __a = np.sin(lowerCAmelCase__ ) __a = theta_a * t __a = np.sin(lowerCAmelCase__ ) __a = np.sin(theta_a - theta_t ) / sin_theta_a __a = sin_theta_t / sin_theta_a __a = sa * va + sa * va if inputs_are_torch: __a = torch.from_numpy(lowerCAmelCase__ ).to(lowerCAmelCase__ ) return va def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[Any] ) -> int: __a = F.normalize(lowerCAmelCase__ , dim=-1 ) __a = F.normalize(lowerCAmelCase__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ) -> List[str]: for param in model.parameters(): __a = value class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a=None , _a=None , _a=None , ): super().__init__() self.register_modules( vae=_a , text_encoder=_a , clip_model=_a , tokenizer=_a , unet=_a , scheduler=_a , feature_extractor=_a , coca_model=_a , coca_tokenizer=_a , coca_transform=_a , ) __a = ( feature_extractor.size if isinstance(feature_extractor.size , _a ) else feature_extractor.size['''shortest_edge'''] ) __a = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , _a ) set_requires_grad(self.clip_model , _a ) def __UpperCAmelCase ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def __UpperCAmelCase ( self ): self.enable_attention_slicing(_a ) def __UpperCAmelCase ( self ): set_requires_grad(self.vae , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.vae , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.unet , _a ) def __UpperCAmelCase ( self ): set_requires_grad(self.unet , _a ) def __UpperCAmelCase ( self , _a , _a , _a ): # get the original timestep using init_timestep __a = min(int(num_inference_steps * strength ) , _a ) __a = max(num_inference_steps - init_timestep , 0 ) __a = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a=None ): if not isinstance(_a , torch.Tensor ): raise ValueError(f'''`image` has to be of type `torch.Tensor` but is {type(_a )}''' ) __a = image.to(device=_a , dtype=_a ) if isinstance(_a , _a ): __a = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_a ) ] __a = torch.cat(_a , dim=0 ) else: __a = self.vae.encode(_a ).latent_dist.sample(_a ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 0.1_8215 * init_latents __a = init_latents.repeat_interleave(_a , dim=0 ) __a = randn_tensor(init_latents.shape , generator=_a , device=_a , dtype=_a ) # get latents __a = self.scheduler.add_noise(_a , _a , _a ) __a = init_latents return latents def __UpperCAmelCase ( self , _a ): __a = self.coca_transform(_a ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): __a = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) __a = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def __UpperCAmelCase ( self , _a , _a ): __a = self.feature_extractor.preprocess(_a ) __a = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() __a = self.clip_model.get_image_features(_a ) __a = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_a ) __a = image_embeddings_clip.repeat_interleave(_a , dim=0 ) return image_embeddings_clip @torch.enable_grad() def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): __a = latents.detach().requires_grad_() __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a , encoder_hidden_states=_a ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): __a = self.scheduler.alphas_cumprod[timestep] __a = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __a = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 __a = torch.sqrt(_a ) __a = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , _a ): __a = self.scheduler.sigmas[index] __a = latents - sigma * noise_pred else: raise ValueError(f'''scheduler type {type(self.scheduler )} not supported''' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 1 / 0.1_8215 * sample __a = self.vae.decode(_a ).sample __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = transforms.Resize(self.feature_extractor_size )(_a ) __a = self.normalize(_a ).to(latents.dtype ) __a = self.clip_model.get_image_features(_a ) __a = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_a ) __a = spherical_dist_loss(_a , _a ).mean() * clip_guidance_scale __a = -torch.autograd.grad(_a , _a )[0] if isinstance(self.scheduler , _a ): __a = latents.detach() + grads * (sigma**2) __a = noise_pred_original else: __a = noise_pred_original - torch.sqrt(_a ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , _a , _a , _a = None , _a = None , _a = 512 , _a = 512 , _a = 0.6 , _a = 50 , _a = 7.5 , _a = 1 , _a = 0.0 , _a = 100 , _a = None , _a = "pil" , _a = True , _a = 0.8 , _a = 0.1 , _a = 0.1 , ): if isinstance(_a , _a ) and len(_a ) != batch_size: raise ValueError(f'''You have passed {batch_size} batch_size, but only {len(_a )} generators.''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if isinstance(_a , torch.Generator ) and batch_size > 1: __a = [generator] + [None] * (batch_size - 1) __a = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] __a = [x[0] for x in coca_is_none if x[1]] __a = ''', '''.join(_a ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(_a ): raise ValueError( f'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' f'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) __a = self.get_image_description(_a ) if style_prompt is None: if len(_a ): raise ValueError( f'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' f''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) __a = self.get_image_description(_a ) # get prompt text embeddings for content and style __a = self.tokenizer( _a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=_a , return_tensors='''pt''' , ) __a = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] __a = self.tokenizer( _a , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=_a , return_tensors='''pt''' , ) __a = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] __a = slerp(_a , _a , _a ) # duplicate text embeddings for each generation per prompt __a = text_embeddings.repeat_interleave(_a , dim=0 ) # set timesteps __a = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) __a = {} if accepts_offset: __a = 1 self.scheduler.set_timesteps(_a , **_a ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) __a , __a = self.get_timesteps(_a , _a , self.device ) __a = timesteps[:1].repeat(_a ) # Preprocess image __a = preprocess(_a , _a , _a ) __a = self.prepare_latents( _a , _a , _a , text_embeddings.dtype , self.device , _a ) __a = preprocess(_a , _a , _a ) __a = self.prepare_latents( _a , _a , _a , text_embeddings.dtype , self.device , _a ) __a = slerp(_a , _a , _a ) if clip_guidance_scale > 0: __a = self.get_clip_image_embeddings(_a , _a ) __a = self.get_clip_image_embeddings(_a , _a ) __a = slerp( _a , _a , _a ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __a = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __a = content_text_input.input_ids.shape[-1] __a = self.tokenizer([''''''] , padding='''max_length''' , max_length=_a , return_tensors='''pt''' ) __a = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt __a = uncond_embeddings.repeat_interleave(_a , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __a = 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`. __a = (batch_size, self.unet.config.in_channels, height // 8, width // 8) __a = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps __a = torch.randn(_a , generator=_a , device='''cpu''' , dtype=_a ).to( self.device ) else: __a = torch.randn(_a , generator=_a , device=self.device , dtype=_a ) else: if latents.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) __a = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __a = 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] __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta # check if the scheduler accepts generator __a = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: __a = generator with self.progress_bar(total=_a ): for i, t in enumerate(_a ): # expand the latents if we are doing classifier free guidance __a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __a = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __a = self.unet(_a , _a , encoder_hidden_states=_a ).sample # perform classifier free guidance if do_classifier_free_guidance: __a , __a = noise_pred.chunk(2 ) __a = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: __a = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) __a , __a = self.cond_fn( _a , _a , _a , _a , _a , _a , _a , ) # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __a = 1 / 0.1_8215 * latents __a = self.vae.decode(_a ).sample __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_a ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=_a , nsfw_content_detected=_a )
65
0
"""simple docstring""" import numpy as np import torch from torch.utils.data import Dataset from utils import logger class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a , _a ): __a = params __a = np.array(A__ ) __a = np.array([len(A__ ) 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 , _a ): return (self.token_ids[index], self.lengths[index]) def __len__( self ): return len(self.lengths ) def __UpperCAmelCase ( self ): 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 ): __a = self.params.max_model_input_size __a = self.lengths > max_len logger.info(f'''Splitting {sum(A__ )} too long sequences.''' ) def divide_chunks(_a , _a ): return [l[i : i + n] for i in range(0 , len(A__ ) , A__ )] __a = [] __a = [] if self.params.mlm: __a = self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""] else: __a = 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: __a = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: __a = np.insert(A__ , 0 , A__ ) if sub_s[-1] != sep_id: __a = np.insert(A__ , len(A__ ) , A__ ) assert len(A__ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(A__ ) new_tok_ids.extend(A__ ) new_lengths.extend([len(A__ ) for l in sub_seqs] ) __a = np.array(A__ ) __a = np.array(A__ ) def __UpperCAmelCase ( self ): __a = len(self ) __a = self.lengths > 11 __a = self.token_ids[indices] __a = self.lengths[indices] __a = len(self ) logger.info(f'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def __UpperCAmelCase ( self ): if "unk_token" not in self.params.special_tok_ids: return else: __a = self.params.special_tok_ids["""unk_token"""] __a = len(self ) __a = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) __a = (unk_occs / self.lengths) < 0.5 __a = self.token_ids[indices] __a = self.lengths[indices] __a = len(self ) logger.info(f'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def __UpperCAmelCase ( self ): 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 , _a ): __a = [t[0] for t in batch] __a = [t[1] for t in batch] assert len(A__ ) == len(A__ ) # Max for paddings __a = max(A__ ) # Pad token ids if self.params.mlm: __a = self.params.special_tok_ids["""pad_token"""] else: __a = self.params.special_tok_ids["""unk_token"""] __a = [list(t.astype(A__ ) ) + [pad_idx] * (max_seq_len_ - len(A__ )) for t in token_ids] assert len(tk_ ) == len(A__ ) assert all(len(A__ ) == max_seq_len_ for t in tk_ ) __a = torch.tensor(tk_ ) # (bs, max_seq_len_) __a = torch.tensor(A__ ) # (bs) return tk_t, lg_t
720
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowercase_ = abspath(join(dirname(dirname(dirname(__file__))), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def lowercase ( lowerCAmelCase__ : List[Any] ) -> str: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int ) -> Union[str, Any]: from transformers.testing_utils import pytest_terminal_summary_main __a = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(lowerCAmelCase__ , id=lowerCAmelCase__ )
65
0
"""simple docstring""" import os import sys import unittest lowercase_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path lowercase_ = os.path.join(git_repo_path, "src", "transformers") lowercase_ = """ {0} = None """ lowercase_ = """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) """ lowercase_ = """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = find_backend(''' _import_structure["models.albert"].append("AlbertTokenizerFast")''' ) self.assertIsNone(UpperCamelCase__ ) __a = find_backend(''' if not is_tokenizers_available():''' ) self.assertEqual(UpperCamelCase__ , '''tokenizers''' ) __a = find_backend(''' if not is_tensorflow_text_available():''' ) self.assertEqual(UpperCamelCase__ , '''tensorflow_text''' ) __a = find_backend(''' if not (is_sentencepiece_available() and is_tokenizers_available()):''' ) self.assertEqual(UpperCamelCase__ , '''sentencepiece_and_tokenizers''' ) __a = find_backend( ''' if not (is_sentencepiece_available() and is_tensorflow_text_available()):''' ) self.assertEqual(UpperCamelCase__ , '''sentencepiece_and_tensorflow_text''' ) __a = find_backend( ''' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):''' ) self.assertEqual(UpperCamelCase__ , '''sentencepiece_and_tokenizers_and_vision''' ) def __UpperCAmelCase ( self ): __a = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('''torch''' , UpperCamelCase__ ) self.assertIn('''tensorflow_text''' , UpperCamelCase__ ) self.assertIn('''sentencepiece_and_tokenizers''' , UpperCamelCase__ ) # Likewise, we can't assert on the exact content of a key self.assertIn('''BertModel''' , objects['''torch'''] ) self.assertIn('''TFBertModel''' , objects['''tf'''] ) self.assertIn('''FlaxBertModel''' , objects['''flax'''] ) self.assertIn('''BertModel''' , objects['''torch'''] ) self.assertIn('''TFBertTokenizer''' , objects['''tensorflow_text'''] ) self.assertIn('''convert_slow_tokenizer''' , objects['''sentencepiece_and_tokenizers'''] ) def __UpperCAmelCase ( self ): __a = create_dummy_object('''CONSTANT''' , '''\'torch\'''' ) self.assertEqual(UpperCamelCase__ , '''\nCONSTANT = None\n''' ) __a = create_dummy_object('''function''' , '''\'torch\'''' ) self.assertEqual( UpperCamelCase__ , '''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' ) __a = ''' class FakeClass(metaclass=DummyObject): _backends = \'torch\' def __init__(self, *args, **kwargs): requires_backends(self, \'torch\') ''' __a = create_dummy_object('''FakeClass''' , '''\'torch\'''' ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def __UpperCAmelCase ( self ): __a = '''# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, ["torch"]) class FakeClass(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) ''' __a = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} ) self.assertEqual(dummy_files['''torch'''] , UpperCamelCase__ )
721
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase_ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __UpperCAmelCase : Any = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __UpperCAmelCase : Any = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __UpperCAmelCase : Dict = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def __UpperCAmelCase ( self , _a , _a , _a ): __a = ZeroShotClassificationPipeline( model=_a , tokenizer=_a , candidate_labels=['''polics''', '''health'''] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def __UpperCAmelCase ( self , _a , _a ): __a = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics''' ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) # No kwarg __a = classifier('''Who are you voting for in 2020?''' , ['''politics'''] ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics'''] ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics, public health''' ) self.assertEqual( _a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) __a = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health'''] ) self.assertEqual( _a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) __a = classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''This text is about {}''' ) self.assertEqual(_a , {'''sequence''': ANY(_a ), '''labels''': [ANY(_a )], '''scores''': [ANY(_a )]} ) # https://github.com/huggingface/transformers/issues/13846 __a = classifier(['''I am happy'''] , ['''positive''', '''negative'''] ) self.assertEqual( _a , [ {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} for i in range(1 ) ] , ) __a = classifier(['''I am happy''', '''I am sad'''] , ['''positive''', '''negative'''] ) self.assertEqual( _a , [ {'''sequence''': ANY(_a ), '''labels''': [ANY(_a ), ANY(_a )], '''scores''': [ANY(_a ), ANY(_a )]} for i in range(2 ) ] , ) with self.assertRaises(_a ): classifier('''''' , candidate_labels='''politics''' ) with self.assertRaises(_a ): classifier(_a , candidate_labels='''politics''' ) with self.assertRaises(_a ): classifier('''Who are you voting for in 2020?''' , candidate_labels='''''' ) with self.assertRaises(_a ): classifier('''Who are you voting for in 2020?''' , candidate_labels=_a ) with self.assertRaises(_a ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''Not formatting template''' , ) with self.assertRaises(_a ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template=_a , ) self.run_entailment_id(_a ) def __UpperCAmelCase ( self , _a ): __a = zero_shot_classifier.model.config __a = config.labelaid __a = zero_shot_classifier.entailment_id __a = {'''LABEL_0''': 0, '''LABEL_1''': 1, '''LABEL_2''': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) __a = {'''entailment''': 0, '''neutral''': 1, '''contradiction''': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __a = {'''ENTAIL''': 0, '''NON-ENTAIL''': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __a = {'''ENTAIL''': 2, '''NEUTRAL''': 1, '''CONTR''': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) __a = original_labelaid self.assertEqual(_a , zero_shot_classifier.entailment_id ) @require_torch def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( '''Who are you voting for in 2020?''' * 100 , candidate_labels=['''politics''', '''public health''', '''science'''] ) @require_torch def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @require_tf def __UpperCAmelCase ( self ): __a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''tf''' , ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @slow @require_torch def __UpperCAmelCase ( self ): __a = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''pt''' ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) __a = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=_a , ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , ) @slow @require_tf def __UpperCAmelCase ( self ): __a = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''tf''' ) __a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) __a = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=_a , ) self.assertEqual( nested_simplify(_a ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , )
65
0
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict ) -> int: # Initialise PyTorch model __a = MobileBertConfig.from_json_file(lowerCAmelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) __a = MobileBertForPreTraining(lowerCAmelCase__ ) # Load weights from tf checkpoint __a = load_tf_weights_in_mobilebert(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowerCAmelCase__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--mobilebert_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained MobileBERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) lowercase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
700
"""simple docstring""" import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowercase ( lowerCAmelCase__ : Optional[int] ) -> int: monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pytest.fixture def lowercase ( lowerCAmelCase__ : Any ) -> Any: class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a ): __a = metric_id class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Any = [MetricMock(__SCREAMING_SNAKE_CASE ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']] def __UpperCAmelCase ( self ): return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() ) @pytest.mark.parametrize( '''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple ) -> Optional[int]: if "tmp_path" in args: __a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(lowerCAmelCase__ , match='''https://huggingface.co/docs/evaluate''' ): func(*lowerCAmelCase__ )
65
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int ) -> List[Any]: if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(SCREAMING_SNAKE_CASE_ , n - 1 , SCREAMING_SNAKE_CASE_ ) * a) % mod else: __a = binary_exponentiation(SCREAMING_SNAKE_CASE_ , n / 2 , SCREAMING_SNAKE_CASE_ ) return (b * b) % mod # a prime number lowercase_ = 7_0_1 lowercase_ = 1_0_0_0_0_0_0_0_0_0 lowercase_ = 1_0 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
701
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> int: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or number < 0: raise ValueError('''Input must be a non-negative integer''' ) __a = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = ['image_processor', 'tokenizer'] __UpperCAmelCase : str = 'LayoutLMv3ImageProcessor' __UpperCAmelCase : Union[str, Any] = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast') def __init__( self , _a=None , _a=None , **_a ): __a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _a , ) __a = kwargs.pop('''feature_extractor''' ) __a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_a , _a ) def __call__( self , _a , _a = None , _a = None , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ): if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) # first, apply the image processor __a = self.image_processor(images=_a , return_tensors=_a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_a , _a ): __a = [text] # add batch dimension (as the image processor always adds a batch dimension) __a = features['words'] __a = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) # add pixel values __a = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __a = self.get_overflowing_images(_a , encoded_inputs['''overflow_to_sample_mapping'''] ) __a = images return encoded_inputs def __UpperCAmelCase ( self , _a , _a ): __a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_a ) != len(_a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f''' {len(_a )} and {len(_a )}''' ) return images_with_overflow def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.batch_decode(*_a , **_a ) def __UpperCAmelCase ( self , *_a , **_a ): return self.tokenizer.decode(*_a , **_a ) @property def __UpperCAmelCase ( self ): return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _a , ) return self.image_processor_class @property def __UpperCAmelCase ( self ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _a , ) return self.image_processor
702
"""simple docstring""" import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[Any] ) -> str: assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int ) -> Tuple: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( '''features''' , [ None, {'''text''': '''string'''}, {'''text''': '''int32'''}, {'''text''': '''float32'''}, ] , ) def lowercase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Union[str, Any] ) -> Optional[int]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) __a = TextDatasetReader(lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict ) -> Optional[Any]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , split=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any] ) -> Dict: if issubclass(lowerCAmelCase__ , lowerCAmelCase__ ): __a = text_path elif issubclass(lowerCAmelCase__ , lowerCAmelCase__ ): __a = [text_path] __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Union[str, Any]=("train",) ) -> Optional[Any]: assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) for split in splits: __a = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def lowercase ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any] ) -> Union[str, Any]: __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __a = TextDatasetReader({'''train''': text_path} , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( '''features''' , [ None, {'''text''': '''string'''}, {'''text''': '''int32'''}, {'''text''': '''float32'''}, ] , ) def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] ) -> str: __a = tmp_path / '''cache''' # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" __a = {'''text''': '''string'''} __a = features.copy() if features else default_expected_features __a = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) __a = TextDatasetReader({'''train''': text_path} , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple ) -> Dict: if split: __a = {split: text_path} else: __a = '''train''' __a = {'''train''': text_path, '''test''': text_path} __a = tmp_path / '''cache''' __a = {'''text''': '''string'''} __a = TextDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_text_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() )
65
0
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } lowercase_ = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } lowercase_ = {"facebook/blenderbot_small-90M": 5_1_2} def lowercase ( lowerCAmelCase__ : Dict ) -> int: __a = set() __a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __a = char __a = set(__lowercase ) return pairs class __lowerCAmelCase ( __A ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = VOCAB_FILES_NAMES __UpperCAmelCase : str = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : List[Any] = ['input_ids', 'attention_mask'] def __init__( self , _a , _a , _a="__start__" , _a="__end__" , _a="__unk__" , _a="__null__" , **_a , ): super().__init__(unk_token=_a , bos_token=_a , eos_token=_a , pad_token=_a , **_a ) with open(_a , encoding='''utf-8''' ) as vocab_handle: __a = json.load(_a ) __a = {v: k for k, v in self.encoder.items()} with open(_a , encoding='''utf-8''' ) as merges_handle: __a = merges_handle.read().split('''\n''' )[1:-1] __a = [tuple(merge.split() ) for merge in merges] __a = dict(zip(_a , range(len(_a ) ) ) ) __a = {} @property def __UpperCAmelCase ( self ): return len(self.encoder ) def __UpperCAmelCase ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def __UpperCAmelCase ( self , _a ): if token in self.cache: return self.cache[token] __a = re.sub('''([.,!?()])''' , R''' \1''' , _a ) __a = re.sub('''(\')''' , R''' \1 ''' , _a ) __a = re.sub(R'''\s{2,}''' , ''' ''' , _a ) if "\n" in token: __a = token.replace('''\n''' , ''' __newln__''' ) __a = token.split(''' ''' ) __a = [] for token in tokens: if not len(_a ): continue __a = token.lower() __a = tuple(_a ) __a = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) __a = get_pairs(_a ) if not pairs: words.append(_a ) continue while True: __a = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __a = bigram __a = [] __a = 0 while i < len(_a ): try: __a = word.index(_a , _a ) new_word.extend(word[i:j] ) __a = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __a = tuple(_a ) __a = new_word if len(_a ) == 1: break else: __a = get_pairs(_a ) __a = '@@ '.join(_a ) __a = word[:-4] __a = word words.append(_a ) return " ".join(_a ) def __UpperCAmelCase ( self , _a ): __a = [] __a = re.findall(R'''\S+\n?''' , _a ) for token in words: split_tokens.extend(list(self.bpe(_a ).split(''' ''' ) ) ) return split_tokens def __UpperCAmelCase ( self , _a ): __a = token.lower() return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def __UpperCAmelCase ( self , _a ): return self.decoder.get(_a , self.unk_token ) def __UpperCAmelCase ( self , _a ): __a = ' '.join(_a ).replace('''@@ ''' , '''''' ).strip() return out_string def __UpperCAmelCase ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_a , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '''\n''' ) __a = 0 with open(_a , '''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 _a : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __a = token_index writer.write(''' '''.join(_a ) + '''\n''' ) index += 1 return vocab_file, merge_file
703
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Any ) -> int: if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) __a = str(bin(__snake_case ) )[2:] # remove the leading "0b" __a = str(bin(__snake_case ) )[2:] # remove the leading "0b" __a = max(len(__snake_case ) , len(__snake_case ) ) return "0b" + "".join( str(int(char_a != char_b ) ) for char_a, char_b in zip(a_binary.zfill(__snake_case ) , b_binary.zfill(__snake_case ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
704
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir("fixtures/test_sentencepiece_bpe_char.model") @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = SpeechTaTokenizer __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = True def __UpperCAmelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing __a = SpeechTaTokenizer(_a ) __a = AddedToken('''<mask>''' , lstrip=_a , rstrip=_a ) __a = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self , _a ): __a = '''this is a test''' __a = '''this is a test''' return input_text, output_text def __UpperCAmelCase ( self , _a , _a=False , _a=20 , _a=5 ): __a , __a = self.get_input_output_texts(_a ) __a = tokenizer.encode(_a , add_special_tokens=_a ) __a = tokenizer.decode(_a , clean_up_tokenization_spaces=_a ) return text, ids def __UpperCAmelCase ( self ): __a = '''<pad>''' __a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def __UpperCAmelCase ( self ): __a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(_a ) , 81 ) def __UpperCAmelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __UpperCAmelCase ( self ): __a = self.get_tokenizers(do_lower_case=_a ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) __a = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] __a = tokenizer.add_tokens(_a ) __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) self.assertEqual(_a , _a ) self.assertEqual(_a , len(_a ) ) self.assertEqual(_a , all_size + len(_a ) ) __a = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=_a ) self.assertGreaterEqual(len(_a ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) __a = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} __a = tokenizer.add_special_tokens(_a ) __a = tokenizer.vocab_size __a = len(_a ) self.assertNotEqual(_a , 0 ) self.assertEqual(_a , _a ) self.assertEqual(_a , len(_a ) ) self.assertEqual(_a , all_size_a + len(_a ) ) __a = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=_a ) self.assertGreaterEqual(len(_a ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a = self.get_tokenizer() __a = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(_a , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) __a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) __a = tokenizer.convert_tokens_to_ids(_a ) # fmt: off self.assertListEqual(_a , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on __a = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def __UpperCAmelCase ( self ): # Use custom sequence because this tokenizer does not handle numbers. __a = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off __a = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=_a , )
65
0
"""simple docstring""" import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class __lowerCAmelCase ( __a ): '''simple docstring''' __UpperCAmelCase : int = 0 __UpperCAmelCase : bool = False __UpperCAmelCase : float = 3.0 class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): # If no defaults are changed, `to_kwargs` returns an empty dict. self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {'''a''': 2} ) self.assertDictEqual(MockClass(a=2 , b=snake_case__ ).to_kwargs() , {'''a''': 2, '''b''': True} ) self.assertDictEqual(MockClass(a=2 , c=2.25 ).to_kwargs() , {'''a''': 2, '''c''': 2.25} ) @require_cuda def __UpperCAmelCase ( self ): # If no defaults are changed, `to_kwargs` returns an empty dict. __a = GradScalerKwargs(init_scale=1_024 , growth_factor=2 ) AcceleratorState._reset_state() __a = Accelerator(mixed_precision='''fp16''' , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) __a = accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 1_024.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 2_000 ) self.assertEqual(scaler._enabled , snake_case__ ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] execute_subprocess_async(snake_case__ , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = DistributedDataParallelKwargs(bucket_cap_mb=1_5, find_unused_parameters=True) lowercase_ = Accelerator(kwargs_handlers=[ddp_scaler]) lowercase_ = torch.nn.Linear(1_0_0, 2_0_0) lowercase_ = accelerator.prepare(model) # Check the values changed in kwargs lowercase_ = '''''' lowercase_ = model.bucket_bytes_cap // (1_0_2_4 * 1_0_2_4) if observed_bucket_cap_map != 1_5: error_msg += F"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += F"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += F"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += F"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += F"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
705
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Any = ['input_features', 'attention_mask'] def __init__( self , _a=80 , _a=16_000 , _a=0.0 , _a=10 , _a=25 , _a="hamming_window" , _a=3_2768.0 , _a=0.97 , _a=1.0 , _a=True , _a=True , _a=False , **_a , ): super().__init__(feature_size=_a , sampling_rate=_a , padding_value=_a , **_a ) __a = feature_size __a = sampling_rate __a = padding_value __a = hop_length __a = win_length __a = frame_signal_scale __a = preemphasis_coeff __a = mel_floor __a = normalize_means __a = normalize_vars __a = win_function __a = return_attention_mask __a = win_length * sampling_rate // 1_000 __a = hop_length * sampling_rate // 1_000 __a = optimal_fft_length(self.sample_size ) __a = (self.n_fft // 2) + 1 def __UpperCAmelCase ( self , _a ): if self.win_function == "hamming_window": __a = window_function(window_length=self.sample_size , name=self.win_function , periodic=_a ) else: __a = window_function(window_length=self.sample_size , name=self.win_function ) __a = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) __a = spectrogram( one_waveform * self.frame_signal_scale , window=_a , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=_a , preemphasis=self.preemphasis_coeff , mel_filters=_a , mel_floor=self.mel_floor , log_mel='''log''' , ) return msfc_features.T def __UpperCAmelCase ( self , _a , _a , _a ): # make sure we normalize float32 arrays if self.normalize_means: __a = x[:input_length].mean(axis=0 ) __a = np.subtract(_a , _a ) if self.normalize_vars: __a = x[:input_length].std(axis=0 ) __a = np.divide(_a , _a ) if input_length < x.shape[0]: __a = padding_value # make sure array is in float32 __a = x.astype(np.floataa ) return x def __UpperCAmelCase ( self , _a , _a = None ): __a = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(_a , _a , self.padding_value ) for x, n in zip(_a , _a )] def __call__( self , _a , _a = False , _a = None , _a = False , _a = None , _a = None , _a = None , _a = None , **_a , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with''' f''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __a = isinstance(_a , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) __a = is_batched_numpy or ( isinstance(_a , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __a = [np.asarray(_a , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_a , np.ndarray ): __a = np.asarray(_a , dtype=np.floataa ) elif isinstance(_a , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __a = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __a = [raw_speech] # extract fbank features __a = [self._extract_mfsc_features(_a ) for one_waveform in raw_speech] # convert into correct format for padding __a = BatchFeature({'''input_features''': features} ) __a = self.pad( _a , padding=_a , max_length=_a , truncation=_a , pad_to_multiple_of=_a , return_attention_mask=_a , **_a , ) # make sure list is in array format __a = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , _a ): __a = [np.asarray(_a , dtype=np.floataa ) for feature in input_features] __a = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __a = [np.asarray(_a , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: __a = ( np.array(_a , dtype=np.intaa ) if self._get_padding_strategies(_a , max_length=_a ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) __a = self.normalize( padded_inputs['''input_features'''] , attention_mask=_a ) if return_tensors is not None: __a = padded_inputs.convert_to_tensors(_a ) return padded_inputs
65
0
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class __lowerCAmelCase ( datasets.BeamBasedBuilder ): '''simple docstring''' def __UpperCAmelCase ( self ): return datasets.DatasetInfo( features=datasets.Features({'''content''': datasets.Value('''string''' )} ) , supervised_keys=a_ , ) def __UpperCAmelCase ( self , _a , _a ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''examples''': get_test_dummy_examples()} )] def __UpperCAmelCase ( self , _a , _a ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(a_ ) class __lowerCAmelCase ( datasets.BeamBasedBuilder ): '''simple docstring''' def __UpperCAmelCase ( self ): return datasets.DatasetInfo( features=datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string''' )} )} ) , supervised_keys=a_ , ) def __UpperCAmelCase ( self , _a , _a ): return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''examples''': get_test_nested_examples()} ) ] def __UpperCAmelCase ( self , _a , _a ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(a_ ) def lowercase ( ) -> str: return [(i, {"content": content}) for i, content in enumerate(['''foo''', '''bar''', '''foobar'''] )] def lowercase ( ) -> List[Any]: return [(i, {"a": {"b": [content]}}) for i, content in enumerate(['''foo''', '''bar''', '''foobar'''] )] class __lowerCAmelCase ( __lowerCamelCase ): '''simple docstring''' @require_beam def __UpperCAmelCase ( self ): __a = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: __a = DummyBeamDataset(cache_dir=a_ , beam_runner='''DirectRunner''' ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(a_ , builder.name , '''default''' , '''0.0.0''' , f'''{builder.name}-train.arrow''' ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({'''content''': datasets.Value('''string''' )} ) ) __a = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , a_ ) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , a_ ) self.assertDictEqual(dset['''train'''][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset['''train'''][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(a_ , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) ) del dset @require_beam def __UpperCAmelCase ( self ): import apache_beam as beam __a = beam.io.parquetio.WriteToParquet __a = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: __a = DummyBeamDataset(cache_dir=a_ , beam_runner='''DirectRunner''' ) with patch('''apache_beam.io.parquetio.WriteToParquet''' ) as write_parquet_mock: __a = partial(a_ , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( a_ , builder.name , '''default''' , '''0.0.0''' , f'''{builder.name}-train-00000-of-00002.arrow''' ) ) ) self.assertTrue( os.path.exists( os.path.join( a_ , builder.name , '''default''' , '''0.0.0''' , f'''{builder.name}-train-00000-of-00002.arrow''' ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({'''content''': datasets.Value('''string''' )} ) ) __a = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , a_ ) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , a_ ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset['''train''']['''content'''] ) , sorted(['''foo''', '''bar''', '''foobar'''] ) ) self.assertTrue( os.path.exists(os.path.join(a_ , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) ) del dset @require_beam def __UpperCAmelCase ( self ): with tempfile.TemporaryDirectory() as tmp_cache_dir: __a = DummyBeamDataset(cache_dir=a_ ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def __UpperCAmelCase ( self ): __a = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: __a = NestedBeamDataset(cache_dir=a_ , beam_runner='''DirectRunner''' ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(a_ , builder.name , '''default''' , '''0.0.0''' , f'''{builder.name}-train.arrow''' ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string''' )} )} ) ) __a = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , a_ ) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , a_ ) self.assertDictEqual(dset['''train'''][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset['''train'''][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(a_ , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) ) del dset
706
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env' ) @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue_model_parallelism.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_6_0_0, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'roberta-large', 'instance_type': 'ml.p3dn.24xlarge', 'results': {'train_runtime': 1_6_0_0, 'eval_accuracy': 0.3, 'eval_loss': 1.2}, }, ] ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=_a , ) assert hasattr(self , '''env''' ) def __UpperCAmelCase ( self , _a ): # configuration for running training on smdistributed Model Parallel __a = { '''enabled''': True, '''processes_per_host''': 8, } __a = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __a = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __a = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=_a , instance_type=self.instance_type , debugger_hook_config=_a , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 500, } , metric_definitions=self.env.metric_definitions , distribution=_a , py_version='''py36''' , ) def __UpperCAmelCase ( self , _a ): TrainingJobAnalytics(_a ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __UpperCAmelCase ( self , _a ): # create estimator __a = self.create_estimator(_a ) # run training estimator.fit() # result dataframe __a = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __a = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __a = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 999_999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , _a )
65
0
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): lowercase_ = "pt" elif is_tf_available(): lowercase_ = "tf" else: lowercase_ = "jax" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Dict = PerceiverTokenizer __UpperCAmelCase : str = False def __UpperCAmelCase ( self ): super().setUp() __a = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __UpperCAmelCase ( self ): return PerceiverTokenizer.from_pretrained('''deepmind/language-perceiver''' ) def __UpperCAmelCase ( self , **_a ): return self.tokenizer_class.from_pretrained(self.tmpdirname , **_a ) def __UpperCAmelCase ( self , _a , _a=False , _a=20 , _a=5 ): # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for Perceiver because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. __a = [] for i in range(len(_a ) ): try: __a = tokenizer.decode([i] , clean_up_tokenization_spaces=_a ) except UnicodeDecodeError: pass toks.append((i, tok) ) __a = list(filter(lambda _a : re.match(R'''^[ a-zA-Z]+$''' , t[1] ) , _a ) ) __a = list(filter(lambda _a : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=_a ) , _a ) ) if max_length is not None and len(_a ) > max_length: __a = toks[:max_length] if min_length is not None and len(_a ) < min_length and len(_a ) > 0: while len(_a ) < min_length: __a = toks + toks # toks_str = [t[1] for t in toks] __a = [t[0] for t in toks] # Ensure consistency __a = tokenizer.decode(_a , clean_up_tokenization_spaces=_a ) if " " not in output_txt and len(_a ) > 1: __a = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_a ) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_a ) ) if with_prefix_space: __a = ''' ''' + output_txt __a = tokenizer.encode(_a , add_special_tokens=_a ) return output_txt, output_ids def __UpperCAmelCase ( self ): __a = self.perceiver_tokenizer __a = '''Unicode €.''' __a = tokenizer(_a ) __a = [4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5] self.assertEqual(encoded['''input_ids'''] , _a ) # decoding __a = tokenizer.decode(_a ) self.assertEqual(_a , '''[CLS]Unicode €.[SEP]''' ) __a = tokenizer('''e è é ê ë''' ) __a = [4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5] self.assertEqual(encoded['''input_ids'''] , _a ) # decoding __a = tokenizer.decode(_a ) self.assertEqual(_a , '''[CLS]e è é ê ë[SEP]''' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''' ) ) , '''[CLS]e è é ê ë[SEP]''' ) def __UpperCAmelCase ( self ): __a = self.perceiver_tokenizer __a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] # fmt: off __a = [4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0] # fmt: on __a = tokenizer(_a , padding=_a , return_tensors=_a ) self.assertIsInstance(_a , _a ) if FRAMEWORK != "jax": __a = list(batch.input_ids.numpy()[0] ) else: __a = list(batch.input_ids.tolist()[0] ) self.assertListEqual(_a , _a ) self.assertEqual((2, 38) , batch.input_ids.shape ) self.assertEqual((2, 38) , batch.attention_mask.shape ) def __UpperCAmelCase ( self ): __a = self.perceiver_tokenizer __a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] __a = tokenizer(_a , padding=_a , return_tensors=_a ) # check if input_ids are returned and no decoder_input_ids self.assertIn('''input_ids''' , _a ) self.assertIn('''attention_mask''' , _a ) self.assertNotIn('''decoder_input_ids''' , _a ) self.assertNotIn('''decoder_attention_mask''' , _a ) def __UpperCAmelCase ( self ): __a = self.perceiver_tokenizer __a = [ '''Summary of the text.''', '''Another summary.''', ] __a = tokenizer( text_target=_a , max_length=32 , padding='''max_length''' , truncation=_a , return_tensors=_a ) self.assertEqual(32 , targets['''input_ids'''].shape[1] ) def __UpperCAmelCase ( self ): # safety check on max_len default value so we are sure the test works __a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test __a = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc __a = tempfile.mkdtemp() __a = ''' He is very happy, UNwant\u00E9d,running''' __a = tokenizer.encode(_a , add_special_tokens=_a ) tokenizer.save_pretrained(_a ) __a = tokenizer.__class__.from_pretrained(_a ) __a = after_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) shutil.rmtree(_a ) __a = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): # Isolate this from the other tests because we save additional tokens/etc __a = tempfile.mkdtemp() __a = ''' He is very happy, UNwant\u00E9d,running''' tokenizer.add_tokens(['''bim''', '''bambam'''] ) __a = tokenizer.additional_special_tokens additional_special_tokens.append('''new_additional_special_token''' ) tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} ) __a = tokenizer.encode(_a , add_special_tokens=_a ) tokenizer.save_pretrained(_a ) __a = tokenizer.__class__.from_pretrained(_a ) __a = after_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) __a = tokenizer.__class__.from_pretrained(_a , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(_a ) def __UpperCAmelCase ( self ): __a = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(_a ) with open(os.path.join(_a , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file: __a = json.load(_a ) with open(os.path.join(_a , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file: __a = json.load(_a ) __a = [f'''<extra_id_{i}>''' for i in range(125 )] __a = added_tokens_extra_ids + [ '''an_additional_special_token''' ] __a = added_tokens_extra_ids + [ '''an_additional_special_token''' ] with open(os.path.join(_a , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(_a , _a ) with open(os.path.join(_a , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(_a , _a ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files __a = tokenizer_class.from_pretrained( _a , ) self.assertIn( '''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens ) self.assertEqual( ['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained __a = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=_a )] __a = tokenizer_class.from_pretrained( _a , additional_special_tokens=_a , ) self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens ) self.assertEqual( ['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''] ) ) , ) def __UpperCAmelCase ( self ): __a = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([178] ) , '''�''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): # The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character # strings and special added tokens as tokens __a = self.get_tokenizers(fast=_a , do_lower_case=_a ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __a = ['''[CLS]''', '''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''s''', '''t''', '''[SEP]'''] __a = tokenizer.convert_tokens_to_string(_a ) self.assertIsInstance(_a , _a )
707
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
65
0
"""simple docstring""" import os from pathlib import Path def lowercase ( ) -> int: '''simple docstring''' from torch.utils.cpp_extension import load __a = Path(_A ).resolve().parent.parent.parent / '''kernels''' / '''deformable_detr''' __a = [ root / filename for filename in [ '''vision.cpp''', os.path.join('''cpu''' , '''ms_deform_attn_cpu.cpp''' ), os.path.join('''cuda''' , '''ms_deform_attn_cuda.cu''' ), ] ] load( '''MultiScaleDeformableAttention''' , _A , with_cuda=_A , extra_include_paths=[str(_A )] , extra_cflags=['''-DWITH_CUDA=1'''] , extra_cuda_cflags=[ '''-DCUDA_HAS_FP16=1''', '''-D__CUDA_NO_HALF_OPERATORS__''', '''-D__CUDA_NO_HALF_CONVERSIONS__''', '''-D__CUDA_NO_HALF2_OPERATORS__''', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
708
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable lowercase_ = {"configuration_gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["GPTNeoXTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXForCausalLM", "GPTNeoXForQuestionAnswering", "GPTNeoXForSequenceClassification", "GPTNeoXForTokenClassification", "GPTNeoXLayer", "GPTNeoXModel", "GPTNeoXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
65
0
"""simple docstring""" from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
709
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=2 , _a=8 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=16 , _a=5 , _a=2 , _a=36 , _a="gelu" , _a=0.0 , _a=0.0 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self ): return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self ): __a = self.get_config() __a = 300 return config def __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraModel(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a ) __a = model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = MraModel(_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , ) __a = model( _a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , ) __a = model(_a , attention_mask=_a , token_type_ids=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraForMaskedLM(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = MraForQuestionAnswering(config=_a ) model.to(_a ) model.eval() __a = model( _a , attention_mask=_a , token_type_ids=_a , start_positions=_a , end_positions=_a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MraForSequenceClassification(_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = MraForTokenClassification(config=_a ) model.to(_a ) model.eval() __a = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a ): __a = self.num_choices __a = MraForMultipleChoice(config=_a ) model.to(_a ) model.eval() __a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) __UpperCAmelCase : str = False __UpperCAmelCase : Any = False __UpperCAmelCase : List[Any] = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Dict = () def __UpperCAmelCase ( self ): __a = MraModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a = type self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = MraModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip(reason='''MRA does not output attentions''' ) def __UpperCAmelCase ( self ): return @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = MraModel.from_pretrained('''uw-madison/mra-base-512-4''' ) __a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4''' ) __a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = 50_265 __a = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ): __a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3''' ) __a = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): __a = model(_a )[0] __a = 50_265 __a = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape , _a ) __a = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1E-4 ) )
65
0
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
710
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> list[str]: if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number_of_bytes!''' ) __a = number_of_bytes // partitions __a = [] for i in range(lowerCAmelCase__ ): __a = i * bytes_per_partition + 1 __a = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" from collections import deque from .hash_table import HashTable class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , *_a , **_a ): super().__init__(*__a , **__a ) def __UpperCAmelCase ( self , _a , _a ): __a = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(__a ) __a = self.values[key] def __UpperCAmelCase ( self ): return ( sum(self.charge_factor - len(__a ) for slot in self.values ) / self.size_table * self.charge_factor ) def __UpperCAmelCase ( self , _a , _a=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(__a ) == 0 ): return key return super()._collision_resolution(__a , __a )
711
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> list: __a = len(lowerCAmelCase__ ) __a = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): __a = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
65
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase_ = { "configuration_gpt_bigcode": ["GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTBigCodeConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTBigCodeForSequenceClassification", "GPTBigCodeForTokenClassification", "GPTBigCodeForCausalLM", "GPTBigCodeModel", "GPTBigCodePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
712
"""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 lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} lowercase_ = { "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" ), }, } lowercase_ = { "allenai/longformer-base-4096": 4_0_9_6, "allenai/longformer-large-4096": 4_0_9_6, "allenai/longformer-large-4096-finetuned-triviaqa": 4_0_9_6, "allenai/longformer-base-4096-extra.pos.embd.only": 4_0_9_6, "allenai/longformer-large-4096-extra.pos.embd.only": 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowercase ( ) -> Union[str, Any]: __a = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __a = bs[:] __a = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCAmelCase__ ) cs.append(2**8 + n ) n += 1 __a = [chr(lowerCAmelCase__ ) for n in cs] return dict(zip(lowerCAmelCase__ , lowerCAmelCase__ ) ) def lowercase ( lowerCAmelCase__ : Tuple ) -> Tuple: __a = set() __a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __a = char return pairs class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = VOCAB_FILES_NAMES __UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Union[str, Any] = ['input_ids', 'attention_mask'] def __init__( self , _a , _a , _a="replace" , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a=False , **_a , ): __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else bos_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else sep_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else cls_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __a = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( errors=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , **_a , ) with open(_a , encoding='''utf-8''' ) as vocab_handle: __a = json.load(_a ) __a = {v: k for k, v in self.encoder.items()} __a = errors # how to handle errors in decoding __a = bytes_to_unicode() __a = {v: k for k, v in self.byte_encoder.items()} with open(_a , encoding='''utf-8''' ) as merges_handle: __a = merges_handle.read().split('''\n''' )[1:-1] __a = [tuple(merge.split() ) for merge in bpe_merges] __a = dict(zip(_a , range(len(_a ) ) ) ) __a = {} __a = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __a = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def __UpperCAmelCase ( self ): return len(self.encoder ) def __UpperCAmelCase ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def __UpperCAmelCase ( self , _a ): if token in self.cache: return self.cache[token] __a = tuple(_a ) __a = get_pairs(_a ) if not pairs: return token while True: __a = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __a , __a = bigram __a = [] __a = 0 while i < len(_a ): try: __a = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __a = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __a = tuple(_a ) __a = new_word if len(_a ) == 1: break else: __a = get_pairs(_a ) __a = ''' '''.join(_a ) __a = word return word def __UpperCAmelCase ( self , _a ): __a = [] for token in re.findall(self.pat , _a ): __a = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(''' ''' ) ) return bpe_tokens def __UpperCAmelCase ( self , _a ): return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def __UpperCAmelCase ( self , _a ): return self.decoder.get(_a ) def __UpperCAmelCase ( self , _a ): __a = ''''''.join(_a ) __a = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def __UpperCAmelCase ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __a = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_a , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '''\n''' ) __a = 0 with open(_a , '''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 _a : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) __a = token_index writer.write(''' '''.join(_a ) + '''\n''' ) index += 1 return vocab_file, merge_file def __UpperCAmelCase ( self , _a , _a = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __a = [self.cls_token_id] __a = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __UpperCAmelCase ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __UpperCAmelCase ( self , _a , _a = None ): __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self , _a , _a=False , **_a ): __a = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): __a = ''' ''' + text return (text, kwargs)
65
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_longformer": [ "LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongformerConfig", "LongformerOnnxConfig", ], "tokenization_longformer": ["LongformerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["LongformerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "LongformerForMaskedLM", "LongformerForMultipleChoice", "LongformerForQuestionAnswering", "LongformerForSequenceClassification", "LongformerForTokenClassification", "LongformerModel", "LongformerPreTrainedModel", "LongformerSelfAttention", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLongformerForMaskedLM", "TFLongformerForMultipleChoice", "TFLongformerForQuestionAnswering", "TFLongformerForSequenceClassification", "TFLongformerForTokenClassification", "TFLongformerModel", "TFLongformerPreTrainedModel", "TFLongformerSelfAttention", ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
713
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "unc-nlp/lxmert-base-uncased": "https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : str = 'lxmert' __UpperCAmelCase : str = {} def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=9_500 , _a=1_600 , _a=400 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1E-12 , _a=9 , _a=5 , _a=5 , _a=2_048 , _a=4 , _a=6.67 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=True , _a=True , **_a , ): __a = vocab_size __a = hidden_size __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = num_qa_labels __a = num_object_labels __a = num_attr_labels __a = l_layers __a = x_layers __a = r_layers __a = visual_feat_dim __a = visual_pos_dim __a = visual_loss_normalizer __a = task_matched __a = task_mask_lm __a = task_obj_predict __a = task_qa __a = visual_obj_loss __a = visual_attr_loss __a = visual_feat_loss __a = {'''vision''': r_layers, '''cross_encoder''': x_layers, '''language''': l_layers} super().__init__(**_a )
65
0
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[int] = AutoencoderKL __UpperCAmelCase : Optional[int] = 'sample' __UpperCAmelCase : List[str] = 1e-2 @property def __UpperCAmelCase ( self ): __a = 4 __a = 3 __a = (32, 32) __a = floats_tensor((batch_size, num_channels) + sizes ).to(_a ) return {"sample": image} @property def __UpperCAmelCase ( self ): return (3, 32, 32) @property def __UpperCAmelCase ( self ): return (3, 32, 32) def __UpperCAmelCase ( self ): __a = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __a = self.dummy_input return init_dict, inputs_dict def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): pass @unittest.skipIf(torch_device == '''mps''' , '''Gradient checkpointing skipped on MPS''' ) def __UpperCAmelCase ( self ): # enable deterministic behavior for gradient checkpointing __a = self.prepare_init_args_and_inputs_for_common() __a = self.model_class(**_a ) model.to(_a ) assert not model.is_gradient_checkpointing and model.training __a = model(**_a ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __a = torch.randn_like(_a ) __a = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __a = self.model_class(**_a ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(_a ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __a = model_a(**_a ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __a = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __a = dict(model.named_parameters() ) __a = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def __UpperCAmelCase ( self ): __a = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' , output_loading_info=_a ) self.assertIsNotNone(_a ) self.assertEqual(len(loading_info['''missing_keys'''] ) , 0 ) model.to(_a ) __a = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __UpperCAmelCase ( self ): __a = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' ) __a = model.to(_a ) model.eval() if torch_device == "mps": __a = torch.manual_seed(0 ) else: __a = torch.Generator(device=_a ).manual_seed(0 ) __a = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __a = image.to(_a ) with torch.no_grad(): __a = model(_a , sample_posterior=_a , generator=_a ).sample __a = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __a = torch.tensor( [ -4.0_078E-01, -3.8_323E-04, -1.2_681E-01, -1.1_462E-01, 2.0_095E-01, 1.0_893E-01, -8.8_247E-02, -3.0_361E-01, -9.8_644E-03, ] ) elif torch_device == "cpu": __a = torch.tensor( [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] ) else: __a = torch.tensor( [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] ) self.assertTrue(torch_all_close(_a , _a , rtol=1E-2 ) ) @slow class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _a , _a ): return f'''gaussian_noise_s={seed}_shape={'_'.join([str(_a ) for s in shape] )}.npy''' def __UpperCAmelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self , _a=0 , _a=(4, 3, 512, 512) , _a=False ): __a = torch.floataa if fpaa else torch.floataa __a = torch.from_numpy(load_hf_numpy(self.get_file_format(_a , _a ) ) ).to(_a ).to(_a ) return image def __UpperCAmelCase ( self , _a="CompVis/stable-diffusion-v1-4" , _a=False ): __a = "fp16" if fpaa else None __a = torch.floataa if fpaa else torch.floataa __a = AutoencoderKL.from_pretrained( _a , subfolder='''vae''' , torch_dtype=_a , revision=_a , ) model.to(_a ).eval() return model def __UpperCAmelCase ( self , _a=0 ): if torch_device == "mps": return torch.manual_seed(_a ) return torch.Generator(device=_a ).manual_seed(_a ) @parameterized.expand( [ # fmt: off [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = self.get_sd_vae_model() __a = self.get_sd_image(_a ) __a = self.get_generator(_a ) with torch.no_grad(): __a = model(_a , generator=_a , sample_posterior=_a ).sample assert sample.shape == image.shape __a = sample[-1, -2:, -2:, :2].flatten().float().cpu() __a = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice ) assert torch_all_close(_a , _a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ] ) @require_torch_gpu def __UpperCAmelCase ( self , _a , _a ): __a = self.get_sd_vae_model(fpaa=_a ) __a = self.get_sd_image(_a , fpaa=_a ) __a = self.get_generator(_a ) with torch.no_grad(): __a = model(_a , generator=_a , sample_posterior=_a ).sample assert sample.shape == image.shape __a = sample[-1, -2:, :2, -2:].flatten().float().cpu() __a = torch.tensor(_a ) assert torch_all_close(_a , _a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = self.get_sd_vae_model() __a = self.get_sd_image(_a ) with torch.no_grad(): __a = model(_a ).sample assert sample.shape == image.shape __a = sample[-1, -2:, -2:, :2].flatten().float().cpu() __a = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice ) assert torch_all_close(_a , _a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ] ) @require_torch_gpu def __UpperCAmelCase ( self , _a , _a ): __a = self.get_sd_vae_model() __a = self.get_sd_image(_a , shape=(3, 4, 64, 64) ) with torch.no_grad(): __a = model.decode(_a ).sample assert list(sample.shape ) == [3, 3, 512, 512] __a = sample[-1, -2:, :2, -2:].flatten().cpu() __a = torch.tensor(_a ) assert torch_all_close(_a , _a , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ] ) @require_torch_gpu def __UpperCAmelCase ( self , _a , _a ): __a = self.get_sd_vae_model(fpaa=_a ) __a = self.get_sd_image(_a , shape=(3, 4, 64, 64) , fpaa=_a ) with torch.no_grad(): __a = model.decode(_a ).sample assert list(sample.shape ) == [3, 3, 512, 512] __a = sample[-1, -2:, :2, -2:].flatten().float().cpu() __a = torch.tensor(_a ) assert torch_all_close(_a , _a , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' ) def __UpperCAmelCase ( self , _a ): __a = self.get_sd_vae_model(fpaa=_a ) __a = self.get_sd_image(_a , shape=(3, 4, 64, 64) , fpaa=_a ) with torch.no_grad(): __a = model.decode(_a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __a = model.decode(_a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(_a , _a , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' ) def __UpperCAmelCase ( self , _a ): __a = self.get_sd_vae_model() __a = self.get_sd_image(_a , shape=(3, 4, 64, 64) ) with torch.no_grad(): __a = model.decode(_a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __a = model.decode(_a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(_a , _a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def __UpperCAmelCase ( self , _a , _a ): __a = self.get_sd_vae_model() __a = self.get_sd_image(_a ) __a = self.get_generator(_a ) with torch.no_grad(): __a = model.encode(_a ).latent_dist __a = dist.sample(generator=_a ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __a = sample[0, -1, -3:, -3:].flatten().cpu() __a = torch.tensor(_a ) __a = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(_a , _a , atol=_a )
714
"""simple docstring""" import itertools import math def lowercase ( lowerCAmelCase__ : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( ) -> int: __a = 2 while True: if is_prime(lowerCAmelCase__ ): yield num num += 1 def lowercase ( lowerCAmelCase__ : int = 10001 ) -> int: return next(itertools.islice(prime_generator() , nth - 1 , lowerCAmelCase__ ) ) if __name__ == "__main__": print(F'''{solution() = }''')
65
0