code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() lowerCAmelCase_ = logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Dict: lowerCAmelCase__ : Tuple = UniSpeechSatForSequenceClassification.from_pretrained(UpperCamelCase , config=UpperCamelCase ) lowerCAmelCase__ : Any = downstream_dict['''projector.weight'''] lowerCAmelCase__ : List[Any] = downstream_dict['''projector.bias'''] lowerCAmelCase__ : Any = downstream_dict['''model.post_net.linear.weight'''] lowerCAmelCase__ : str = downstream_dict['''model.post_net.linear.bias'''] return model def __lowerCAmelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> List[Any]: lowerCAmelCase__ : Tuple = UniSpeechSatForAudioFrameClassification.from_pretrained(UpperCamelCase , config=UpperCamelCase ) lowerCAmelCase__ : List[Any] = downstream_dict['''model.linear.weight'''] lowerCAmelCase__ : Union[str, Any] = downstream_dict['''model.linear.bias'''] return model def __lowerCAmelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> List[Any]: lowerCAmelCase__ : int = UniSpeechSatForXVector.from_pretrained(UpperCamelCase , config=UpperCamelCase ) lowerCAmelCase__ : Dict = downstream_dict['''connector.weight'''] lowerCAmelCase__ : Optional[int] = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): lowerCAmelCase__ : List[str] = downstream_dict[ F"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] lowerCAmelCase__ : Any = downstream_dict[F"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] lowerCAmelCase__ : str = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] lowerCAmelCase__ : List[Any] = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] lowerCAmelCase__ : Tuple = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] lowerCAmelCase__ : Optional[Any] = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] lowerCAmelCase__ : Dict = downstream_dict['''objective.W'''] return model @torch.no_grad() def __lowerCAmelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Any: lowerCAmelCase__ : str = torch.load(UpperCamelCase , map_location='''cpu''' ) lowerCAmelCase__ : Any = checkpoint['''Downstream'''] lowerCAmelCase__ : List[str] = UniSpeechSatConfig.from_pretrained(UpperCamelCase ) lowerCAmelCase__ : str = WavaVecaFeatureExtractor.from_pretrained( UpperCamelCase , return_attention_mask=UpperCamelCase , do_normalize=UpperCamelCase ) lowerCAmelCase__ : Optional[Any] = hf_config.architectures[0] if arch.endswith('''ForSequenceClassification''' ): lowerCAmelCase__ : Any = convert_classification(UpperCamelCase , UpperCamelCase , UpperCamelCase ) elif arch.endswith('''ForAudioFrameClassification''' ): lowerCAmelCase__ : Dict = convert_diarization(UpperCamelCase , UpperCamelCase , UpperCamelCase ) elif arch.endswith('''ForXVector''' ): lowerCAmelCase__ : Any = convert_xvector(UpperCamelCase , UpperCamelCase , UpperCamelCase ) else: raise NotImplementedError(F"""S3PRL weights conversion is not supported for {arch}""" ) if hf_config.use_weighted_layer_sum: lowerCAmelCase__ : List[Any] = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(UpperCamelCase ) hf_model.save_pretrained(UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument( """--base_model_name""", default=None, type=str, help="""Name of the huggingface pretrained base model.""" ) parser.add_argument("""--config_path""", default=None, type=str, help="""Path to the huggingface classifier config.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to the s3prl checkpoint.""") parser.add_argument("""--model_dump_path""", default=None, type=str, help="""Path to the final converted model.""") lowerCAmelCase_ = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
678
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir("""fixtures/test_sentencepiece_no_bos.model""") @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( _lowercase , unittest.TestCase ): A__ = PegasusTokenizer A__ = PegasusTokenizerFast A__ = True A__ = True def __magic_name__( self ): super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ : Union[str, Any] = PegasusTokenizer(__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __magic_name__( self ): return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def __magic_name__( self , **__UpperCAmelCase ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __magic_name__( self , __UpperCAmelCase ): return ("This is a test", "This is a test") def __magic_name__( self ): lowerCAmelCase__ : Optional[Any] = '''</s>''' lowerCAmelCase__ : Optional[int] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def __magic_name__( self ): lowerCAmelCase__ : Tuple = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<pad>''' ) self.assertEqual(vocab_keys[1] , '''</s>''' ) self.assertEqual(vocab_keys[-1] , '''v''' ) self.assertEqual(len(__UpperCAmelCase ) , 1103 ) def __magic_name__( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __magic_name__( self ): lowerCAmelCase__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) lowerCAmelCase__ : Tuple = self.tokenizer_class.from_pretrained(self.tmpdirname ) lowerCAmelCase__ : int = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) lowerCAmelCase__ : Any = rust_tokenizer([raw_input_str] , return_tensors=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ).input_ids[0] lowerCAmelCase__ : Dict = py_tokenizer([raw_input_str] , return_tensors=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ).input_ids[0] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __magic_name__( self ): lowerCAmelCase__ : Any = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word lowerCAmelCase__ : List[str] = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' lowerCAmelCase__ : Tuple = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] lowerCAmelCase__ : Tuple = tokenizer([raw_input_str] , return_tensors=__UpperCAmelCase ).input_ids[0] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __magic_name__( self ): lowerCAmelCase__ : Dict = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 lowerCAmelCase__ : str = '''To ensure a smooth flow of bank resolutions.''' lowerCAmelCase__ : int = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] lowerCAmelCase__ : List[Any] = tokenizer([raw_input_str] , return_tensors=__UpperCAmelCase ).input_ids[0] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __magic_name__( self ): lowerCAmelCase__ : Optional[int] = ['''This is going to be way too long.''' * 150, '''short example'''] lowerCAmelCase__ : List[str] = ['''not super long but more than 5 tokens''', '''tiny'''] lowerCAmelCase__ : Tuple = self._large_tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , return_tensors='''pt''' ) lowerCAmelCase__ : Optional[int] = self._large_tokenizer( text_target=__UpperCAmelCase , max_length=5 , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(__UpperCAmelCase ) == 2 # input_ids, attention_mask. @slow def __magic_name__( self ): # fmt: off lowerCAmelCase__ : Optional[int] = {'''input_ids''': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='''google/bigbird-pegasus-large-arxiv''' , revision='''ba85d0851d708441f91440d509690f1ab6353415''' , ) @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( _lowercase , unittest.TestCase ): A__ = PegasusTokenizer A__ = PegasusTokenizerFast A__ = True A__ = True def __magic_name__( self ): super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ : List[Any] = PegasusTokenizer(__UpperCAmelCase , offset=0 , mask_token_sent=__UpperCAmelCase , mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __magic_name__( self ): return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def __magic_name__( self , **__UpperCAmelCase ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __magic_name__( self , __UpperCAmelCase ): return ("This is a test", "This is a test") def __magic_name__( self ): lowerCAmelCase__ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) lowerCAmelCase__ : int = self.tokenizer_class.from_pretrained(self.tmpdirname ) lowerCAmelCase__ : str = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) lowerCAmelCase__ : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ).input_ids[0] lowerCAmelCase__ : int = py_tokenizer([raw_input_str] , return_tensors=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ).input_ids[0] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @require_torch def __magic_name__( self ): lowerCAmelCase__ : Optional[Any] = ['''This is going to be way too long.''' * 1000, '''short example'''] lowerCAmelCase__ : int = ['''not super long but more than 5 tokens''', '''tiny'''] lowerCAmelCase__ : Tuple = self._large_tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , return_tensors='''pt''' ) lowerCAmelCase__ : Tuple = self._large_tokenizer( text_target=__UpperCAmelCase , max_length=5 , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(__UpperCAmelCase ) == 2 # input_ids, attention_mask. def __magic_name__( self ): lowerCAmelCase__ : List[str] = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) lowerCAmelCase__ : Union[str, Any] = self._large_tokenizer(__UpperCAmelCase ).input_ids self.assertListEqual( __UpperCAmelCase , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
678
1
from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCamelCase : str = {'''tokenization_wav2vec2_phoneme''': ['''Wav2Vec2PhonemeCTCTokenizer''']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys lowerCamelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
713
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class _UpperCamelCase (enum.Enum ): snake_case_ = 0 snake_case_ = 1 snake_case_ = 2 @add_end_docstrings(a_ ) class _UpperCamelCase (a_ ): snake_case_ = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *__UpperCamelCase , **__UpperCamelCase )-> Optional[int]: super().__init__(*__UpperCamelCase , **__UpperCamelCase ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. __lowerCAmelCase = None if self.model.config.prefix is not None: __lowerCAmelCase = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. __lowerCAmelCase = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = self._sanitize_parameters(prefix=__UpperCamelCase , **self._forward_params ) __lowerCAmelCase = {**self._preprocess_params, **preprocess_params} __lowerCAmelCase = {**self._forward_params, **forward_params} def __UpperCAmelCase ( self , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None , **__UpperCamelCase , )-> int: __lowerCAmelCase = {} if prefix is not None: __lowerCAmelCase = prefix if prefix: __lowerCAmelCase = self.tokenizer( __UpperCamelCase , padding=__UpperCamelCase , add_special_tokens=__UpperCamelCase , return_tensors=self.framework ) __lowerCAmelCase = prefix_inputs["input_ids"].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( F"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected""" " [None, 'hole']" ) __lowerCAmelCase = handle_long_generation preprocess_params.update(__UpperCamelCase ) __lowerCAmelCase = generate_kwargs __lowerCAmelCase = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_full_text`" ) if return_tensors is not None: raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`" ) __lowerCAmelCase = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_tensors`" ) __lowerCAmelCase = ReturnType.TENSORS if return_type is not None: __lowerCAmelCase = return_type if clean_up_tokenization_spaces is not None: __lowerCAmelCase = clean_up_tokenization_spaces if stop_sequence is not None: __lowerCAmelCase = self.tokenizer.encode(__UpperCamelCase , add_special_tokens=__UpperCamelCase ) if len(__UpperCamelCase ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __lowerCAmelCase = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __UpperCAmelCase ( self , *__UpperCamelCase , **__UpperCamelCase )-> List[str]: # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"add_space_before_punct_symbol": True} ) return super()._parse_and_tokenize(*__UpperCamelCase , **__UpperCamelCase ) def __call__( self , __UpperCamelCase , **__UpperCamelCase )-> List[Any]: return super().__call__(__UpperCamelCase , **__UpperCamelCase ) def __UpperCAmelCase ( self , __UpperCamelCase , __UpperCamelCase="" , __UpperCamelCase=None , **__UpperCamelCase )-> int: __lowerCAmelCase = self.tokenizer( prefix + prompt_text , padding=__UpperCamelCase , add_special_tokens=__UpperCamelCase , return_tensors=self.framework ) __lowerCAmelCase = prompt_text if handle_long_generation == "hole": __lowerCAmelCase = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: __lowerCAmelCase = generate_kwargs["max_new_tokens"] else: __lowerCAmelCase = generate_kwargs.get("max_length" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("We cannot infer how many new tokens are expected" ) if cur_len + new_tokens > self.tokenizer.model_max_length: __lowerCAmelCase = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( "We cannot use `hole` to handle this generation the number of desired tokens exceeds the" " models max length" ) __lowerCAmelCase = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: __lowerCAmelCase = inputs["attention_mask"][:, -keep_length:] return inputs def __UpperCAmelCase ( self , __UpperCamelCase , **__UpperCamelCase )-> Optional[Any]: __lowerCAmelCase = model_inputs["input_ids"] __lowerCAmelCase = model_inputs.get("attention_mask" , __UpperCamelCase ) # Allow empty prompts if input_ids.shape[1] == 0: __lowerCAmelCase = None __lowerCAmelCase = None __lowerCAmelCase = 1 else: __lowerCAmelCase = input_ids.shape[0] __lowerCAmelCase = model_inputs.pop("prompt_text" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. __lowerCAmelCase = generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: __lowerCAmelCase = "max_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].max_new_tokens is not None ) if not has_max_new_tokens: __lowerCAmelCase = generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length __lowerCAmelCase = "min_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL __lowerCAmelCase = self.model.generate(input_ids=__UpperCamelCase , attention_mask=__UpperCamelCase , **__UpperCamelCase ) __lowerCAmelCase = generated_sequence.shape[0] if self.framework == "pt": __lowerCAmelCase = generated_sequence.reshape(__UpperCamelCase , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": __lowerCAmelCase = tf.reshape(__UpperCamelCase , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __UpperCAmelCase ( self , __UpperCamelCase , __UpperCamelCase=ReturnType.FULL_TEXT , __UpperCamelCase=True )-> Any: __lowerCAmelCase = model_outputs["generated_sequence"][0] __lowerCAmelCase = model_outputs["input_ids"] __lowerCAmelCase = model_outputs["prompt_text"] __lowerCAmelCase = generated_sequence.numpy().tolist() __lowerCAmelCase = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: __lowerCAmelCase = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text __lowerCAmelCase = self.tokenizer.decode( __UpperCamelCase , skip_special_tokens=__UpperCamelCase , clean_up_tokenization_spaces=__UpperCamelCase , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: __lowerCAmelCase = 0 else: __lowerCAmelCase = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=__UpperCamelCase , clean_up_tokenization_spaces=__UpperCamelCase , ) ) if return_type == ReturnType.FULL_TEXT: __lowerCAmelCase = prompt_text + text[prompt_length:] else: __lowerCAmelCase = text[prompt_length:] __lowerCAmelCase = {"generated_text": all_text} records.append(__UpperCamelCase ) return records
290
0
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin A_ : str = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class __snake_case ( snake_case__ , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ReformerTokenizer lowerCamelCase__ = ReformerTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = False lowerCamelCase__ = True def __UpperCamelCase ( self ): super().setUp() snake_case__ : Union[str, Any] = ReformerTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCamelCase ( self ): snake_case__ : str = """<s>""" snake_case__ : Optional[int] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Tuple = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<unk>""" ) self.assertEqual(vocab_keys[1] , """<s>""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , 1_0_0_0 ) def __UpperCamelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_0 ) def __UpperCamelCase ( self ): if not self.test_rust_tokenizer: return snake_case__ : Optional[Any] = self.get_tokenizer() snake_case__ : int = self.get_rust_tokenizer() snake_case__ : Optional[int] = """I was born in 92000, and this is falsé.""" snake_case__ : str = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = rust_tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = rust_tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.get_rust_tokenizer() snake_case__ : Tuple = tokenizer.encode(__SCREAMING_SNAKE_CASE ) snake_case__ : str = rust_tokenizer.encode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE=1_5 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : Dict = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # Simple input snake_case__ : int = """This is a simple input""" snake_case__ : Optional[Any] = ["""This is a simple input 1""", """This is a simple input 2"""] snake_case__ : Optional[int] = ("""This is a simple input""", """This is a pair""") snake_case__ : Optional[Any] = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__SCREAMING_SNAKE_CASE , tokenizer_r.encode , __SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Simple input self.assertRaises(__SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , __SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Simple input self.assertRaises( __SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , __SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , padding="""max_length""" , ) # Pair input self.assertRaises(__SCREAMING_SNAKE_CASE , tokenizer_r.encode , __SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Pair input self.assertRaises(__SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , __SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Pair input self.assertRaises( __SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , __SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , padding="""max_length""" , ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): snake_case__ : int = ReformerTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2] , ) snake_case__ : Union[str, Any] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) snake_case__ : Tuple = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4] , ) snake_case__ : Tuple = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def __UpperCamelCase ( self ): return ReformerTokenizer.from_pretrained("""google/reformer-crime-and-punishment""" ) @slow def __UpperCamelCase ( self ): snake_case__ : int = """Hello World!""" snake_case__ : Union[str, Any] = [1_2_6, 3_2, 2_6_2, 1_5_2, 3_8, 7_2, 2_8_7] self.assertListEqual(__SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(__SCREAMING_SNAKE_CASE ) ) @slow def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth""" ) snake_case__ : str = [ 1_0_8, 2_6_5, 2_4, 1_1_1, 4, 2_5_8, 1_5_6, 3_5, 2_8, 2_7_5, 3, 2_5_9, 2_9_7, 2_6_0, 8_4, 4, 3_5, 1_1_0, 4_4, 8, 2_5_9, 9_1, 2_6_8, 2_1, 1_1, 2_0_9, 2_7_4, 1_0_9, 2_6_6, 2_7_7, 1_1_7, 8_6, 9_3, 3_1_5, 2_5_8, 2_7_8, 2_5_8, 2_7_7, 2_5_8, 0, 2_5_8, 2_8_8, 2_5_8, 3_1_9, 2_5_8, 0, 2_5_8, 0, 2_5_8, 0, 2_5_8, 0, 2_5_8, 2_8_7, 2_5_8, 3_1_5, 2_5_8, 2_8_9, 2_5_8, 2_7_8, 9_9, 2_6_9, 2_6_6, 2_6_2, 8, 2_5_9, 2_4_1, 4, 2_1_7, 2_3_0, 2_6_8, 2_6_6, 5_5, 1_6_8, 1_0_6, 7_5, 1_9_3, 2_6_6, 2_2_3, 2_7, 4_9, 2_6, 2_8_2, 2_5, 2_6_4, 2_9_9, 1_9, 2_6, 0, 2_5_8, 2_7_7, 1_1_7, 8_6, 9_3, 1_7_6, 1_8_3, 2_7_0, 1_1, 2_6_2, 4_2, 6_1, 2_6_5, ] self.assertListEqual(__SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(__SCREAMING_SNAKE_CASE ) ) @require_torch @slow def __UpperCamelCase ( self ): import torch from transformers import ReformerConfig, ReformerModel # Build sequence snake_case__ : Optional[Any] = list(self.big_tokenizer.get_vocab().keys() )[:1_0] snake_case__ : str = """ """.join(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.big_tokenizer.encode_plus(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) snake_case__ : Dict = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors="""pt""" ) snake_case__ : str = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) snake_case__ : Any = encoded_sequence["""input_ids"""].shape snake_case__ : Optional[Any] = ReformerModel(__SCREAMING_SNAKE_CASE ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__SCREAMING_SNAKE_CASE ) model(**__SCREAMING_SNAKE_CASE ) @slow def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = {"""input_ids""": [[1_0_8, 2_6_5, 2_4, 1_1_1, 4, 2_5_8, 1_5_6, 7, 5_1, 2_7_9, 5_8, 7, 7_6, 2_5, 6_9, 2_7_8], [1_4_0, 2_4_3, 2_6_4, 1_3_4, 1_7, 2_6_7, 7_7, 2_6_3, 2_2, 2_6_2, 2_9_7, 2_5_8, 3_0_4, 1_7_7, 2_7_9, 2_6_6, 1_4, 8_9, 1_3, 3_5, 2_6_1, 2_9_9, 2_7_2, 1_3_7, 2_7_5, 2_7_8]], """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]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 snake_case__ : Dict = [ """This is a very simple sentence.""", """The quick brown fox jumps over the lazy dog.""", ] self.tokenizer_integration_test_util( expected_encoding=__SCREAMING_SNAKE_CASE , model_name="""google/reformer-crime-and-punishment""" , revision="""0e6c3decb8211d49bf881013425dc8b0448b3f5a""" , padding=__SCREAMING_SNAKE_CASE , sequences=__SCREAMING_SNAKE_CASE , )
38
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import 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.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.g4dn.xlarge""", """results""": {"""train_runtime""": 6_50, """eval_accuracy""": 0.6, """eval_loss""": 0.9}, }, { """framework""": """tensorflow""", """script""": """run_tf.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.g4dn.xlarge""", """results""": {"""train_runtime""": 6_00, """eval_accuracy""": 0.3, """eval_loss""": 0.9}, }, ] ) class __UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) -> int: """simple docstring""" 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=SCREAMING_SNAKE_CASE , ) assert hasattr(self , "env" ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=1 ) -> Tuple: """simple docstring""" # 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}-single''' , instance_count=SCREAMING_SNAKE_CASE , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE , hyperparameters={**self.env.hyperparameters, "model_name_or_path": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version="py36" , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" TrainingJobAnalytics(SCREAMING_SNAKE_CASE ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" # create estimator UpperCamelCase = self.create_estimator() # run training estimator.fit() # result dataframe UpperCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis UpperCamelCase = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"] ) UpperCamelCase = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping UpperCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get("TrainingTimeInSeconds" , 999999 ) ) # 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} , SCREAMING_SNAKE_CASE )
606
0
class __A : '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = name lowerCamelCase__ = value lowerCamelCase__ = weight def __repr__( self ): '''simple docstring''' return F'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def __lowerCamelCase ( self ): '''simple docstring''' return self.value def __lowerCamelCase ( self ): '''simple docstring''' return self.name def __lowerCamelCase ( self ): '''simple docstring''' return self.weight def __lowerCamelCase ( self ): '''simple docstring''' return self.value / self.weight def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase__ = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): menu.append(Things(name[i] ,value[i] ,weight[i] ) ) return menu def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase__ = sorted(SCREAMING_SNAKE_CASE_ ,key=SCREAMING_SNAKE_CASE_ ,reverse=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = [] lowerCamelCase__ , lowerCamelCase__ = 0.0, 0.0 for i in range(len(SCREAMING_SNAKE_CASE_ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def lowerCAmelCase__() -> Tuple: '''simple docstring''' pass if __name__ == "__main__": import doctest doctest.testmod()
714
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging _a = logging.get_logger(__name__) class __A : '''simple docstring''' lowerCAmelCase_ = None @experimental def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> Tuple: '''simple docstring''' if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( __snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) return _map_with_joblib(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> int: '''simple docstring''' lowerCamelCase__ = num_proc if num_proc <= len(__snake_case ) else len(__snake_case ) lowerCamelCase__ = [] # We organize the splits ourselve (contiguous splits) for index in range(__snake_case ): lowerCamelCase__ = len(__snake_case ) // num_proc lowerCamelCase__ = len(__snake_case ) % num_proc lowerCamelCase__ = div * index + min(__snake_case ,__snake_case ) lowerCamelCase__ = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc) ) if len(__snake_case ) != sum(len(i[1] ) for i in split_kwds ): raise ValueError( F'Error dividing inputs iterable among processes. ' F'Total number of objects {len(__snake_case )}, ' F'length: {sum(len(i[1] ) for i in split_kwds )}' ) logger.info( F'Spawning {num_proc} processes for {len(__snake_case )} objects in slices of {[len(i[1] ) for i in split_kwds]}' ) lowerCamelCase__ , lowerCamelCase__ = None, None if not disable_tqdm: lowerCamelCase__ , lowerCamelCase__ = (RLock(),), tqdm.set_lock with Pool(__snake_case ,initargs=__snake_case ,initializer=__snake_case ) as pool: lowerCamelCase__ = pool.map(__snake_case ,__snake_case ) logger.info(F'Finished {num_proc} processes' ) lowerCamelCase__ = [obj for proc_res in mapped for obj in proc_res] logger.info(F'Unpacked {len(__snake_case )} objects' ) return mapped def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> List[str]: '''simple docstring''' import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name ,n_jobs=__snake_case ): return joblib.Parallel()( joblib.delayed(__snake_case )((function, obj, types, None, True, None) ) for obj in iterable ) @experimental @contextlib.contextmanager def lowerCAmelCase__(__snake_case ) -> int: '''simple docstring''' lowerCamelCase__ = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: lowerCamelCase__ = None
29
0
"""simple docstring""" import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def _lowerCAmelCase ( lowerCamelCase__ : Any, lowerCamelCase__ : Optional[int], lowerCamelCase__ : int, lowerCamelCase__ : Union[str, Any]="attention" ) -> str: _SCREAMING_SNAKE_CASE : int = params[f'''{prefix}/layers_{i}/{layer_name}/key/kernel'''] _SCREAMING_SNAKE_CASE : str = params[f'''{prefix}/layers_{i}/{layer_name}/out/kernel'''] _SCREAMING_SNAKE_CASE : int = params[f'''{prefix}/layers_{i}/{layer_name}/query/kernel'''] _SCREAMING_SNAKE_CASE : Any = params[f'''{prefix}/layers_{i}/{layer_name}/value/kernel'''] return k, o, q, v def _lowerCAmelCase ( lowerCamelCase__ : int, lowerCamelCase__ : Optional[int], lowerCamelCase__ : List[Any], lowerCamelCase__ : Optional[int]=False ) -> List[Any]: if split_mlp_wi: _SCREAMING_SNAKE_CASE : Optional[Any] = params[f'''{prefix}/layers_{i}/mlp/wi_0/kernel'''] _SCREAMING_SNAKE_CASE : Dict = params[f'''{prefix}/layers_{i}/mlp/wi_1/kernel'''] _SCREAMING_SNAKE_CASE : Union[str, Any] = (wi_a, wi_a) else: _SCREAMING_SNAKE_CASE : Union[str, Any] = params[f'''{prefix}/layers_{i}/mlp/wi/kernel'''] _SCREAMING_SNAKE_CASE : int = params[f'''{prefix}/layers_{i}/mlp/wo/kernel'''] return wi, wo def _lowerCAmelCase ( lowerCamelCase__ : Union[str, Any], lowerCamelCase__ : List[str], lowerCamelCase__ : List[Any], lowerCamelCase__ : Dict ) -> Optional[int]: return params[f'''{prefix}/layers_{i}/{layer_name}/scale'''] def _lowerCAmelCase ( lowerCamelCase__ : Dict, *, lowerCamelCase__ : List[str], lowerCamelCase__ : Union[str, Any] ) -> str: _SCREAMING_SNAKE_CASE : Union[str, Any] = traverse_util.flatten_dict(variables["target"] ) _SCREAMING_SNAKE_CASE : int = {"/".join(lowerCamelCase__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi _SCREAMING_SNAKE_CASE : Tuple = "encoder/layers_0/mlp/wi_0/kernel" in old print("Split MLP:", lowerCamelCase__ ) _SCREAMING_SNAKE_CASE : Optional[Any] = collections.OrderedDict() # Shared embeddings. _SCREAMING_SNAKE_CASE : int = old["token_embedder/embedding"] # Encoder. for i in range(lowerCamelCase__ ): # Block i, layer 0 (Self Attention). _SCREAMING_SNAKE_CASE : Tuple = tax_layer_norm_lookup(lowerCamelCase__, lowerCamelCase__, "encoder", "pre_attention_layer_norm" ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = tax_attention_lookup(lowerCamelCase__, lowerCamelCase__, "encoder", "attention" ) _SCREAMING_SNAKE_CASE : Any = layer_norm _SCREAMING_SNAKE_CASE : Dict = k.T _SCREAMING_SNAKE_CASE : List[str] = o.T _SCREAMING_SNAKE_CASE : Dict = q.T _SCREAMING_SNAKE_CASE : List[str] = v.T # Block i, layer 1 (MLP). _SCREAMING_SNAKE_CASE : Dict = tax_layer_norm_lookup(lowerCamelCase__, lowerCamelCase__, "encoder", "pre_mlp_layer_norm" ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Tuple = tax_mlp_lookup(lowerCamelCase__, lowerCamelCase__, "encoder", lowerCamelCase__ ) _SCREAMING_SNAKE_CASE : Optional[Any] = layer_norm if split_mlp_wi: _SCREAMING_SNAKE_CASE : str = wi[0].T _SCREAMING_SNAKE_CASE : Optional[int] = wi[1].T else: _SCREAMING_SNAKE_CASE : Optional[Any] = wi.T _SCREAMING_SNAKE_CASE : Any = wo.T _SCREAMING_SNAKE_CASE : Optional[int] = old[ "encoder/relpos_bias/rel_embedding" ].T _SCREAMING_SNAKE_CASE : str = old["encoder/encoder_norm/scale"] if not is_encoder_only: # Decoder. for i in range(lowerCamelCase__ ): # Block i, layer 0 (Self Attention). _SCREAMING_SNAKE_CASE : Union[str, Any] = tax_layer_norm_lookup(lowerCamelCase__, lowerCamelCase__, "decoder", "pre_self_attention_layer_norm" ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = tax_attention_lookup(lowerCamelCase__, lowerCamelCase__, "decoder", "self_attention" ) _SCREAMING_SNAKE_CASE : Optional[int] = layer_norm _SCREAMING_SNAKE_CASE : List[Any] = k.T _SCREAMING_SNAKE_CASE : Union[str, Any] = o.T _SCREAMING_SNAKE_CASE : Any = q.T _SCREAMING_SNAKE_CASE : Tuple = v.T # Block i, layer 1 (Cross Attention). _SCREAMING_SNAKE_CASE : List[Any] = tax_layer_norm_lookup(lowerCamelCase__, lowerCamelCase__, "decoder", "pre_cross_attention_layer_norm" ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = tax_attention_lookup(lowerCamelCase__, lowerCamelCase__, "decoder", "encoder_decoder_attention" ) _SCREAMING_SNAKE_CASE : Dict = layer_norm _SCREAMING_SNAKE_CASE : Union[str, Any] = k.T _SCREAMING_SNAKE_CASE : Optional[int] = o.T _SCREAMING_SNAKE_CASE : List[Any] = q.T _SCREAMING_SNAKE_CASE : List[Any] = v.T # Block i, layer 2 (MLP). _SCREAMING_SNAKE_CASE : int = tax_layer_norm_lookup(lowerCamelCase__, lowerCamelCase__, "decoder", "pre_mlp_layer_norm" ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = tax_mlp_lookup(lowerCamelCase__, lowerCamelCase__, "decoder", lowerCamelCase__ ) _SCREAMING_SNAKE_CASE : List[str] = layer_norm if split_mlp_wi: _SCREAMING_SNAKE_CASE : Tuple = wi[0].T _SCREAMING_SNAKE_CASE : Any = wi[1].T else: _SCREAMING_SNAKE_CASE : Optional[Any] = wi.T _SCREAMING_SNAKE_CASE : Any = wo.T _SCREAMING_SNAKE_CASE : int = old["decoder/decoder_norm/scale"] _SCREAMING_SNAKE_CASE : str = old[ "decoder/relpos_bias/rel_embedding" ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: _SCREAMING_SNAKE_CASE : Any = old["decoder/logits_dense/kernel"].T return new def _lowerCAmelCase ( lowerCamelCase__ : Optional[int], lowerCamelCase__ : Tuple ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: _SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict["shared.weight"] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: _SCREAMING_SNAKE_CASE : Any = state_dict["shared.weight"] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("Using shared word embeddings as lm_head." ) _SCREAMING_SNAKE_CASE : Dict = state_dict["shared.weight"] return state_dict def _lowerCAmelCase ( lowerCamelCase__ : List[Any], lowerCamelCase__ : int, lowerCamelCase__ : Optional[Any], lowerCamelCase__ : List[str] ) -> int: _SCREAMING_SNAKE_CASE : List[Any] = checkpoints.load_tax_checkpoint(lowerCamelCase__ ) _SCREAMING_SNAKE_CASE : List[str] = convert_tax_to_pytorch(lowerCamelCase__, num_layers=config.num_layers, is_encoder_only=lowerCamelCase__ ) _SCREAMING_SNAKE_CASE : Optional[Any] = make_state_dict(lowerCamelCase__, lowerCamelCase__ ) model.load_state_dict(lowerCamelCase__, strict=lowerCamelCase__ ) def _lowerCAmelCase ( lowerCamelCase__ : Optional[int], lowerCamelCase__ : Tuple, lowerCamelCase__ : Tuple, lowerCamelCase__ : Union[str, Any] = False ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : Optional[Any] = TaConfig.from_json_file(lowerCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: _SCREAMING_SNAKE_CASE : Tuple = TaEncoderModel(lowerCamelCase__ ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = TaForConditionalGeneration(lowerCamelCase__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(lowerCamelCase__ ) # Verify that we can load the checkpoint. model.from_pretrained(lowerCamelCase__ ) print("Done" ) if __name__ == "__main__": lowercase_ : Optional[int] = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) lowercase_ : Union[str, Any] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
572
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": __magic_name__ =argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--original_config_file''', type=str, required=True, help='''The YAML config file corresponding to the original architecture.''', ) parser.add_argument( '''--num_in_channels''', default=None, type=int, help='''The number of input channels. If `None` number of input channels will be automatically inferred.''', ) parser.add_argument( '''--image_size''', default=512, type=int, help=( '''The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2''' ''' Base. Use 768 for Stable Diffusion v2.''' ), ) parser.add_argument( '''--extract_ema''', action='''store_true''', help=( '''Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights''' ''' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield''' ''' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.''' ), ) parser.add_argument( '''--upcast_attention''', action='''store_true''', help=( '''Whether the attention computation should always be upcasted. This is necessary when running stable''' ''' diffusion 2.1.''' ), ) parser.add_argument( '''--from_safetensors''', action='''store_true''', help='''If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.''', ) parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') def __UpperCamelCase ( A ): if string == "True": return True elif string == "False": return False else: raise ValueError(f"could not parse string as bool {string}" ) parser.add_argument( '''--use_linear_projection''', help='''Override for use linear projection''', required=False, type=parse_bool ) parser.add_argument('''--cross_attention_dim''', help='''Override for cross attention_dim''', required=False, type=int) __magic_name__ =parser.parse_args() __magic_name__ =download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
415
0
"""simple docstring""" import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml lowerCAmelCase_ = NewType('''DataClass''', Any) lowerCAmelCase_ = NewType('''DataClassType''', Any) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Any: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).""" ) def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> Callable[[str], Any]: _SCREAMING_SNAKE_CASE : Union[str, Any] = {str(__SCREAMING_SNAKE_CASE ): choice for choice in choices} return lambda __SCREAMING_SNAKE_CASE : str_to_choice.get(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowerCamelCase_(*, __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = dataclasses.MISSING , __SCREAMING_SNAKE_CASE = dataclasses.MISSING , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , )-> dataclasses.Field: if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls _SCREAMING_SNAKE_CASE : Optional[int] = {} if aliases is not None: _SCREAMING_SNAKE_CASE : Dict = aliases if help is not None: _SCREAMING_SNAKE_CASE : Optional[int] = help return dataclasses.field(metadata=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , default_factory=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class _snake_case ( __snake_case ): """simple docstring""" a = 42 def __init__( self : Union[str, Any] , _A : Union[DataClassType, Iterable[DataClassType]] , **_A : str): """simple docstring""" if "formatter_class" not in kwargs: _SCREAMING_SNAKE_CASE : Optional[int] = ArgumentDefaultsHelpFormatter super().__init__(**_A) if dataclasses.is_dataclass(_A): _SCREAMING_SNAKE_CASE : List[str] = [dataclass_types] _SCREAMING_SNAKE_CASE : Optional[Any] = list(_A) for dtype in self.dataclass_types: self._add_dataclass_arguments(_A) @staticmethod def _lowerCAmelCase ( _A : ArgumentParser , _A : dataclasses.Field): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = f"""--{field.name}""" _SCREAMING_SNAKE_CASE : int = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , _A): raise RuntimeError( """Unresolved type detected, which should have been done with the help of """ """`typing.get_type_hints` method by default""") _SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop("""aliases""" , []) if isinstance(_A , _A): _SCREAMING_SNAKE_CASE : int = [aliases] _SCREAMING_SNAKE_CASE : Tuple = getattr(field.type , """__origin__""" , field.type) if origin_type is Union or (hasattr(_A , """UnionType""") and isinstance(_A , types.UnionType)): if str not in field.type.__args__ and ( len(field.type.__args__) != 2 or type(_A) not in field.type.__args__ ): raise ValueError( """Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because""" """ the argument parser only supports one type per argument.""" f""" Problem encountered in field '{field.name}'.""") if type(_A) not in field.type.__args__: # filter `str` in Union _SCREAMING_SNAKE_CASE : Union[str, Any] = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] _SCREAMING_SNAKE_CASE : Optional[Any] = getattr(field.type , """__origin__""" , field.type) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) _SCREAMING_SNAKE_CASE : int = ( field.type.__args__[0] if isinstance(_A , field.type.__args__[1]) else field.type.__args__[1] ) _SCREAMING_SNAKE_CASE : Optional[Any] = getattr(field.type , """__origin__""" , field.type) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) _SCREAMING_SNAKE_CASE : List[Any] = {} if origin_type is Literal or (isinstance(field.type , _A) and issubclass(field.type , _A)): if origin_type is Literal: _SCREAMING_SNAKE_CASE : Optional[Any] = field.type.__args__ else: _SCREAMING_SNAKE_CASE : int = [x.value for x in field.type] _SCREAMING_SNAKE_CASE : List[str] = make_choice_type_function(kwargs["""choices"""]) if field.default is not dataclasses.MISSING: _SCREAMING_SNAKE_CASE : Any = field.default else: _SCREAMING_SNAKE_CASE : Union[str, Any] = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument _SCREAMING_SNAKE_CASE : int = copy(_A) # Hack because type=bool in argparse does not behave as we want. _SCREAMING_SNAKE_CASE : Optional[Any] = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. _SCREAMING_SNAKE_CASE : Dict = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way _SCREAMING_SNAKE_CASE : str = default # This tells argparse we accept 0 or 1 value after --field_name _SCREAMING_SNAKE_CASE : str = """?""" # This is the value that will get picked if we do --field_name (without value) _SCREAMING_SNAKE_CASE : List[Any] = True elif isclass(_A) and issubclass(_A , _A): _SCREAMING_SNAKE_CASE : Tuple = field.type.__args__[0] _SCREAMING_SNAKE_CASE : Optional[int] = """+""" if field.default_factory is not dataclasses.MISSING: _SCREAMING_SNAKE_CASE : Union[str, Any] = field.default_factory() elif field.default is dataclasses.MISSING: _SCREAMING_SNAKE_CASE : Optional[Any] = True else: _SCREAMING_SNAKE_CASE : List[str] = field.type if field.default is not dataclasses.MISSING: _SCREAMING_SNAKE_CASE : int = field.default elif field.default_factory is not dataclasses.MISSING: _SCREAMING_SNAKE_CASE : Union[str, Any] = field.default_factory() else: _SCREAMING_SNAKE_CASE : Any = True parser.add_argument(_A , *_A , **_A) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): _SCREAMING_SNAKE_CASE : Union[str, Any] = False parser.add_argument(f"""--no_{field.name}""" , action="""store_false""" , dest=field.name , **_A) def _lowerCAmelCase ( self : Optional[Any] , _A : DataClassType): """simple docstring""" if hasattr(_A , """_argument_group_name"""): _SCREAMING_SNAKE_CASE : List[str] = self.add_argument_group(dtype._argument_group_name) else: _SCREAMING_SNAKE_CASE : str = self try: _SCREAMING_SNAKE_CASE : Dict[str, type] = get_type_hints(_A) except NameError: raise RuntimeError( f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """ """removing line of `from __future__ import annotations` which opts in Postponed """ """Evaluation of Annotations (PEP 563)""") except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 1_0) and "unsupported operand type(s) for |" in str(_A): _SCREAMING_SNAKE_CASE : List[str] = """.""".join(map(_A , sys.version_info[:3])) raise RuntimeError( f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """ """line of `from __future__ import annotations` which opts in union types as """ """`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To """ """support Python versions that lower than 3.10, you need to use """ """`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of """ """`X | None`.""") from ex raise for field in dataclasses.fields(_A): if not field.init: continue _SCREAMING_SNAKE_CASE : Any = type_hints[field.name] self._parse_dataclass_field(_A , _A) def _lowerCAmelCase ( self : Any , _A : Union[str, Any]=None , _A : Union[str, Any]=False , _A : Union[str, Any]=True , _A : Union[str, Any]=None , _A : int=None , ): """simple docstring""" if args_file_flag or args_filename or (look_for_args_file and len(sys.argv)): _SCREAMING_SNAKE_CASE : List[str] = [] if args_filename: args_files.append(Path(_A)) elif look_for_args_file and len(sys.argv): args_files.append(Path(sys.argv[0]).with_suffix(""".args""")) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values _SCREAMING_SNAKE_CASE : int = ArgumentParser() args_file_parser.add_argument(_A , type=_A , action="""append""") # Use only remaining args for further parsing (remove the args_file_flag) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = args_file_parser.parse_known_args(args=_A) _SCREAMING_SNAKE_CASE : List[str] = vars(_A).get(args_file_flag.lstrip("""-""") , _A) if cmd_args_file_paths: args_files.extend([Path(_A) for p in cmd_args_file_paths]) _SCREAMING_SNAKE_CASE : Optional[Any] = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last _SCREAMING_SNAKE_CASE : str = file_args + args if args is not None else file_args + sys.argv[1:] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self.parse_known_args(args=_A) _SCREAMING_SNAKE_CASE : Union[str, Any] = [] for dtype in self.dataclass_types: _SCREAMING_SNAKE_CASE : Dict = {f.name for f in dataclasses.fields(_A) if f.init} _SCREAMING_SNAKE_CASE : List[str] = {k: v for k, v in vars(_A).items() if k in keys} for k in keys: delattr(_A , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = dtype(**_A) outputs.append(_A) if len(namespace.__dict__) > 0: # additional namespace. outputs.append(_A) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}""") return (*outputs,) def _lowerCAmelCase ( self : List[Any] , _A : Dict[str, Any] , _A : bool = False): """simple docstring""" _SCREAMING_SNAKE_CASE : str = set(args.keys()) _SCREAMING_SNAKE_CASE : Dict = [] for dtype in self.dataclass_types: _SCREAMING_SNAKE_CASE : Union[str, Any] = {f.name for f in dataclasses.fields(_A) if f.init} _SCREAMING_SNAKE_CASE : Optional[Any] = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys()) _SCREAMING_SNAKE_CASE : Optional[int] = dtype(**_A) outputs.append(_A) if not allow_extra_keys and unused_keys: raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(_A)}""") return tuple(_A) def _lowerCAmelCase ( self : Optional[int] , _A : str , _A : bool = False): """simple docstring""" with open(Path(_A) , encoding="""utf-8""") as open_json_file: _SCREAMING_SNAKE_CASE : List[str] = json.loads(open_json_file.read()) _SCREAMING_SNAKE_CASE : List[Any] = self.parse_dict(_A , allow_extra_keys=_A) return tuple(_A) def _lowerCAmelCase ( self : Dict , _A : str , _A : bool = False): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = self.parse_dict(yaml.safe_load(Path(_A).read_text()) , allow_extra_keys=_A) return tuple(_A)
635
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''', # See all SEW models at https://huggingface.co/models?filter=sew } class _snake_case ( __snake_case ): """simple docstring""" a = "sew" def __init__( self : List[Any] , _A : Tuple=3_2 , _A : str=7_6_8 , _A : Dict=1_2 , _A : Tuple=1_2 , _A : Optional[Any]=3_0_7_2 , _A : List[str]=2 , _A : Dict="gelu" , _A : Union[str, Any]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.1 , _A : Optional[int]=0.0 , _A : str=0.1 , _A : Tuple=0.1 , _A : Optional[int]=0.02 , _A : Dict=1e-5 , _A : str="group" , _A : Tuple="gelu" , _A : Union[str, Any]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , _A : Optional[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _A : Any=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _A : Tuple=False , _A : Tuple=1_2_8 , _A : int=1_6 , _A : Union[str, Any]=True , _A : Optional[Any]=0.05 , _A : List[Any]=1_0 , _A : Union[str, Any]=2 , _A : Tuple=0.0 , _A : Union[str, Any]=1_0 , _A : Optional[int]=0 , _A : Union[str, Any]="mean" , _A : Optional[int]=False , _A : List[Any]=False , _A : int=2_5_6 , _A : str=0 , _A : Optional[int]=1 , _A : List[Any]=2 , **_A : Dict , ): """simple docstring""" super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A) _SCREAMING_SNAKE_CASE : str = hidden_size _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_norm _SCREAMING_SNAKE_CASE : Optional[int] = feat_extract_activation _SCREAMING_SNAKE_CASE : Dict = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : int = list(_A) _SCREAMING_SNAKE_CASE : str = conv_bias _SCREAMING_SNAKE_CASE : Tuple = num_conv_pos_embeddings _SCREAMING_SNAKE_CASE : List[str] = num_conv_pos_embedding_groups _SCREAMING_SNAKE_CASE : Tuple = len(self.conv_dim) _SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers _SCREAMING_SNAKE_CASE : List[str] = intermediate_size _SCREAMING_SNAKE_CASE : str = squeeze_factor _SCREAMING_SNAKE_CASE : Dict = hidden_act _SCREAMING_SNAKE_CASE : str = num_attention_heads _SCREAMING_SNAKE_CASE : Dict = hidden_dropout _SCREAMING_SNAKE_CASE : Tuple = attention_dropout _SCREAMING_SNAKE_CASE : int = activation_dropout _SCREAMING_SNAKE_CASE : Any = feat_proj_dropout _SCREAMING_SNAKE_CASE : str = final_dropout _SCREAMING_SNAKE_CASE : Union[str, Any] = layerdrop _SCREAMING_SNAKE_CASE : Any = layer_norm_eps _SCREAMING_SNAKE_CASE : int = initializer_range _SCREAMING_SNAKE_CASE : List[Any] = vocab_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" f"""but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)""" f"""= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`.""") # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _SCREAMING_SNAKE_CASE : List[Any] = apply_spec_augment _SCREAMING_SNAKE_CASE : List[Any] = mask_time_prob _SCREAMING_SNAKE_CASE : List[str] = mask_time_length _SCREAMING_SNAKE_CASE : List[Any] = mask_time_min_masks _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_prob _SCREAMING_SNAKE_CASE : int = mask_feature_length _SCREAMING_SNAKE_CASE : List[Any] = mask_feature_min_masks # ctc loss _SCREAMING_SNAKE_CASE : int = ctc_loss_reduction _SCREAMING_SNAKE_CASE : Optional[int] = ctc_zero_infinity # sequence classification _SCREAMING_SNAKE_CASE : Dict = use_weighted_layer_sum _SCREAMING_SNAKE_CASE : List[str] = classifier_proj_size @property def _lowerCAmelCase ( self : Any): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1)
635
1
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _A ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Optional[Any] = IFImgaImgSuperResolutionPipeline lowerCamelCase : Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'} lowerCamelCase : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_image'} ) lowerCamelCase : Tuple = PipelineTesterMixin.required_optional_params - {'latents'} def _a ( self : Any ) -> List[Any]: return self._get_superresolution_dummy_components() def _a ( self : str , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=0 ) -> int: if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __UpperCAmelCase =torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __UpperCAmelCase =torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =floats_tensor((1, 3, 16, 16) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase ={ """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def _a ( self : Optional[Any] ) -> Dict: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def _a ( self : str ) -> str: self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def _a ( self : Optional[Any] ) -> str: # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def _a ( self : Any ) -> Optional[int]: self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def _a ( self : List[Any] ) -> Tuple: self._test_save_load_local() def _a ( self : List[Any] ) -> Union[str, Any]: self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
68
'''simple docstring''' # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union _UpperCamelCase : List[Any] = re.compile(R'^(?P<major>\d+)' R'\.(?P<minor>\d+)' R'\.(?P<patch>\d+)$') @total_ordering @dataclass class _lowercase: """simple docstring""" __lowerCamelCase = 42 __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None def snake_case ( self: Tuple ): __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = _str_to_version_tuple(self.version_str ) def __repr__( self: Any ): return f"""{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}""" @property def snake_case ( self: int ): return self.major, self.minor, self.patch def snake_case ( self: Union[str, Any] ,a: Tuple ): if isinstance(a ,a ): return Version(a ) elif isinstance(a ,a ): return other raise TypeError(f"""{other} (type {type(a )}) cannot be compared to version.""" ) def __eq__( self: Dict ,a: str ): try: __UpperCAmelCase = self._validate_operand(a ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self: Optional[Any] ,a: List[Any] ): __UpperCAmelCase = self._validate_operand(a ) return self.tuple < other.tuple def __hash__( self: List[str] ): return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def snake_case ( cls: Optional[Any] ,a: int ): __UpperCAmelCase = {f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def snake_case ( self: Optional[Any] ): return self.version_str def __snake_case ( lowerCAmelCase : Dict ): __UpperCAmelCase = _VERSION_REG.match(lowerCAmelCase ) if not res: raise ValueError(F"""Invalid version '{version_str}'. Format should be x.y.z with {{x,y,z}} being digits.""" ) return tuple(int(lowerCAmelCase ) for v in [res.group('major' ), res.group('minor' ), res.group('patch' )] ) def __snake_case ( lowerCAmelCase : List[str] ): return ".".join(str(lowerCAmelCase ) for v in version_tuple )
396
0
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def __lowercase ( __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] ): assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def __lowercase ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ): a__ = tmp_path / 'cache' a__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a__ = ParquetDatasetReader(__lowerCAmelCase , cache_dir=__lowerCAmelCase , keep_in_memory=__lowerCAmelCase ).read() _check_parquet_dataset(__lowerCAmelCase , __lowerCAmelCase ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def __lowercase ( __lowerCAmelCase : str , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any ): a__ = tmp_path / 'cache' a__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} 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__ = ParquetDatasetReader(__lowerCAmelCase , features=__lowerCAmelCase , cache_dir=__lowerCAmelCase ).read() _check_parquet_dataset(__lowerCAmelCase , __lowerCAmelCase ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def __lowercase ( __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] ): a__ = tmp_path / 'cache' a__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a__ = ParquetDatasetReader(__lowerCAmelCase , cache_dir=__lowerCAmelCase , split=__lowerCAmelCase ).read() _check_parquet_dataset(__lowerCAmelCase , __lowerCAmelCase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list] ) def __lowercase ( __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : str ): if issubclass(__lowerCAmelCase , __lowerCAmelCase ): a__ = parquet_path elif issubclass(__lowerCAmelCase , __lowerCAmelCase ): a__ = [parquet_path] a__ = tmp_path / 'cache' a__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a__ = ParquetDatasetReader(__lowerCAmelCase , cache_dir=__lowerCAmelCase ).read() _check_parquet_dataset(__lowerCAmelCase , __lowerCAmelCase ) def __lowercase ( __lowerCAmelCase : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any]=("train",) ): assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) for split in splits: a__ = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def __lowercase ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ): a__ = tmp_path / 'cache' a__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a__ = ParquetDatasetReader( {'train': parquet_path} , cache_dir=__lowerCAmelCase , keep_in_memory=__lowerCAmelCase ).read() _check_parquet_datasetdict(__lowerCAmelCase , __lowerCAmelCase ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def __lowercase ( __lowerCAmelCase : int , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[int] ): a__ = tmp_path / 'cache' a__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} 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__ = ParquetDatasetReader({'train': parquet_path} , features=__lowerCAmelCase , cache_dir=__lowerCAmelCase ).read() _check_parquet_datasetdict(__lowerCAmelCase , __lowerCAmelCase ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def __lowercase ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] ): if split: a__ = {split: parquet_path} else: a__ = 'train' a__ = {'train': parquet_path, 'test': parquet_path} a__ = tmp_path / 'cache' a__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a__ = ParquetDatasetReader(__lowerCAmelCase , cache_dir=__lowerCAmelCase ).read() _check_parquet_datasetdict(__lowerCAmelCase , __lowerCAmelCase , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def __lowercase ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int] ): a__ = ParquetDatasetWriter(__lowerCAmelCase , tmp_path / 'foo.parquet' ) assert writer.write() > 0 a__ = pq.ParquetFile(tmp_path / 'foo.parquet' ) a__ = pf.read() assert dataset.data.table == output_table def __lowercase ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] ): a__ = str(shared_datadir / 'test_image_rgb.jpg' ) a__ = {'image': [image_path]} a__ = Features({'image': Image()} ) a__ = Dataset.from_dict(__lowerCAmelCase , features=__lowerCAmelCase ) a__ = ParquetDatasetWriter(__lowerCAmelCase , tmp_path / 'foo.parquet' ) assert writer.write() > 0 a__ = Dataset.from_parquet(str(tmp_path / 'foo.parquet' ) ) assert dataset.features == reloaded_dataset.features a__ = ParquetDatasetReader(str(tmp_path / 'foo.parquet' ) , streaming=__lowerCAmelCase ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( 'feature, expected' , [ (Features({'foo': Value('int32' )} ), None), (Features({'image': Image(), 'foo': Value('int32' )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({'nested': Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def __lowercase ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ): assert get_writer_batch_size(__lowerCAmelCase ) == expected
657
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand snake_case : str = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) snake_case : str = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) snake_case : str = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) snake_case : Tuple = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) snake_case : str = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 14]), ('''2H 5D 3C AS 5S''', False, [14, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [14, 13, 12, 11, 10]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) snake_case : Tuple = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) snake_case : int = ( ('''JH AH TH KH QH''', 23), ('''JH 9H TH KH QH''', 22), ('''JC KH JS JD JH''', 21), ('''KH KC 3S 3H 3D''', 20), ('''8C 9C 5C 3C TC''', 19), ('''JS QS 9H TS KH''', 18), ('''7C 7S KH 2H 7H''', 17), ('''3C KH 5D 5S KH''', 16), ('''QH 8H KD JH 8S''', 15), ('''2D 6D 9D TH 7D''', 14), ) def __lowercase ( ): a__ , a__ = randrange(len(__lowerCAmelCase ) ), randrange(len(__lowerCAmelCase ) ) a__ = ['Loss', 'Tie', 'Win'][(play >= oppo) + (play > oppo)] a__ , a__ = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def __lowercase ( __lowerCAmelCase : int = 1_0_0 ): return (generate_random_hand() for _ in range(__lowerCAmelCase )) @pytest.mark.parametrize('hand, expected' , __lowerCAmelCase ) def __lowercase ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] ): assert PokerHand(__lowerCAmelCase )._is_flush() == expected @pytest.mark.parametrize('hand, expected' , __lowerCAmelCase ) def __lowercase ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Any ): assert PokerHand(__lowerCAmelCase )._is_straight() == expected @pytest.mark.parametrize('hand, expected, card_values' , __lowerCAmelCase ) def __lowercase ( __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Dict ): a__ = PokerHand(__lowerCAmelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('hand, expected' , __lowerCAmelCase ) def __lowercase ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ): assert PokerHand(__lowerCAmelCase )._is_same_kind() == expected @pytest.mark.parametrize('hand, expected' , __lowerCAmelCase ) def __lowercase ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple ): assert PokerHand(__lowerCAmelCase )._hand_type == expected @pytest.mark.parametrize('hand, other, expected' , __lowerCAmelCase ) def __lowercase ( __lowerCAmelCase : List[str] , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] ): assert PokerHand(__lowerCAmelCase ).compare_with(PokerHand(__lowerCAmelCase ) ) == expected @pytest.mark.parametrize('hand, other, expected' , generate_random_hands() ) def __lowercase ( __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple ): assert PokerHand(__lowerCAmelCase ).compare_with(PokerHand(__lowerCAmelCase ) ) == expected def __lowercase ( ): a__ = [PokerHand(__lowerCAmelCase ) for hand in SORTED_HANDS] a__ = poker_hands.copy() shuffle(__lowerCAmelCase ) a__ = chain(sorted(__lowerCAmelCase ) ) for index, hand in enumerate(__lowerCAmelCase ): assert hand == poker_hands[index] def __lowercase ( ): # Test that five high straights are compared correctly. a__ = [PokerHand('2D AC 3H 4H 5S' ), PokerHand('2S 3H 4H 5S 6C' )] pokerhands.sort(reverse=__lowerCAmelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def __lowercase ( ): # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. a__ = PokerHand('2C 4S AS 3D 5C' ) a__ = True a__ = [5, 4, 3, 2, 1_4] for _ in range(1_0 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def __lowercase ( ): # Problem number 54 from Project Euler # Testing from poker_hands.txt file a__ = 0 a__ = os.path.abspath(os.path.dirname(__lowerCAmelCase ) ) a__ = os.path.join(__lowerCAmelCase , 'poker_hands.txt' ) with open(__lowerCAmelCase ) as file_hand: for line in file_hand: a__ = line[:1_4].strip() a__ = line[1_5:].strip() a__ , a__ = PokerHand(__lowerCAmelCase ), PokerHand(__lowerCAmelCase ) a__ = player.compare_with(__lowerCAmelCase ) if output == "Win": answer += 1 assert answer == 3_7_6
657
1
'''simple docstring''' class lowercase_ : """simple docstring""" def __init__( self : Optional[int] ): __lowercase = 0 __lowercase = 0 __lowercase = {} def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,lowercase__ : str ): if vertex not in self.adjacency: __lowercase = {} self.num_vertices += 1 def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : Optional[Any] ,lowercase__ : List[str] ,lowercase__ : Any ): self.add_vertex(lowercase__ ) self.add_vertex(lowercase__ ) if head == tail: return __lowercase = weight __lowercase = weight def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): __lowercase = self.get_edges() for edge in edges: __lowercase , __lowercase , __lowercase = edge edges.remove((tail, head, weight) ) for i in range(len(lowercase__ ) ): __lowercase = list(edges[i] ) edges.sort(key=lambda lowercase__ : e[2] ) for i in range(len(lowercase__ ) - 1 ): if edges[i][2] >= edges[i + 1][2]: __lowercase = edges[i][2] + 1 for edge in edges: __lowercase , __lowercase , __lowercase = edge __lowercase = weight __lowercase = weight def __str__( self : Union[str, Any] ): __lowercase = '''''' for tail in self.adjacency: for head in self.adjacency[tail]: __lowercase = self.adjacency[head][tail] string += F"{head} -> {tail} == {weight}\n" return string.rstrip('''\n''' ) def SCREAMING_SNAKE_CASE ( self : Tuple ): __lowercase = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def SCREAMING_SNAKE_CASE ( self : Optional[int] ): return self.adjacency.keys() @staticmethod def SCREAMING_SNAKE_CASE ( lowercase__ : str=None ,lowercase__ : Any=None ): __lowercase = Graph() if vertices is None: __lowercase = [] if edges is None: __lowercase = [] for vertex in vertices: g.add_vertex(lowercase__ ) for edge in edges: g.add_edge(*lowercase__ ) return g class lowercase_ : """simple docstring""" def __init__( self : List[str] ): __lowercase = {} __lowercase = {} def __len__( self : Dict ): return len(self.parent ) def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : Any ): if item in self.parent: return self.find(lowercase__ ) __lowercase = item __lowercase = 0 return item def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,lowercase__ : Dict ): if item not in self.parent: return self.make_set(lowercase__ ) if item != self.parent[item]: __lowercase = self.find(self.parent[item] ) return self.parent[item] def SCREAMING_SNAKE_CASE ( self : int ,lowercase__ : Tuple ,lowercase__ : Dict ): __lowercase = self.find(lowercase__ ) __lowercase = self.find(lowercase__ ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: __lowercase = roota return roota if self.rank[roota] < self.rank[roota]: __lowercase = roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 __lowercase = roota return roota return None @staticmethod def SCREAMING_SNAKE_CASE ( lowercase__ : Optional[int] ): __lowercase = graph.num_vertices __lowercase = Graph.UnionFind() __lowercase = [] while num_components > 1: __lowercase = {} for vertex in graph.get_vertices(): __lowercase = -1 __lowercase = graph.get_edges() for edge in edges: __lowercase , __lowercase , __lowercase = edge edges.remove((tail, head, weight) ) for edge in edges: __lowercase , __lowercase , __lowercase = edge __lowercase = union_find.find(lowercase__ ) __lowercase = union_find.find(lowercase__ ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: __lowercase = [head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: __lowercase = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: __lowercase , __lowercase , __lowercase = cheap_edge[vertex] if union_find.find(lowercase__ ) != union_find.find(lowercase__ ): union_find.union(lowercase__ ,lowercase__ ) mst_edges.append(cheap_edge[vertex] ) __lowercase = num_components - 1 __lowercase = Graph.build(edges=lowercase__ ) return mst
41
'''simple docstring''' import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class lowercase_ : """simple docstring""" def __init__( self : Dict ,lowercase__ : Dict ,lowercase__ : int=1_3 ,lowercase__ : List[str]=7 ,lowercase__ : int=True ,lowercase__ : int=True ,lowercase__ : Union[str, Any]=True ,lowercase__ : List[Any]=True ,lowercase__ : str=9_9 ,lowercase__ : Optional[Any]=3_2 ,lowercase__ : Union[str, Any]=5 ,lowercase__ : List[Any]=4 ,lowercase__ : str=3_7 ,lowercase__ : Tuple="gelu" ,lowercase__ : List[Any]=0.1 ,lowercase__ : Dict=0.1 ,lowercase__ : int=1_2_8 ,lowercase__ : Dict=3_2 ,lowercase__ : Dict=1_6 ,lowercase__ : Any=2 ,lowercase__ : int=0.0_2 ,lowercase__ : List[str]=3 ,lowercase__ : Dict=4 ,lowercase__ : Optional[int]=None ,): __lowercase = parent __lowercase = batch_size __lowercase = seq_length __lowercase = is_training __lowercase = use_input_mask __lowercase = use_token_type_ids __lowercase = use_labels __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_act __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_size __lowercase = type_sequence_label_size __lowercase = initializer_range __lowercase = num_labels __lowercase = num_choices __lowercase = scope def SCREAMING_SNAKE_CASE ( self : Optional[int] ): __lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __lowercase = None if self.use_input_mask: __lowercase = random_attention_mask([self.batch_size, self.seq_length] ) __lowercase = None if self.use_token_type_ids: __lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) __lowercase = None __lowercase = None __lowercase = None if self.use_labels: __lowercase = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) __lowercase = ids_tensor([self.batch_size] ,self.num_choices ) __lowercase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): return NezhaConfig( 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=lowercase__ ,initializer_range=self.initializer_range ,) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = self.prepare_config_and_inputs() __lowercase = True __lowercase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __lowercase = 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 SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : Union[str, Any] ,lowercase__ : List[str] ,lowercase__ : List[str] ,lowercase__ : List[str] ,lowercase__ : Tuple ,lowercase__ : Tuple ,lowercase__ : str ): __lowercase = NezhaModel(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model(lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ) __lowercase = model(lowercase__ ,token_type_ids=lowercase__ ) __lowercase = model(lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : Dict ,lowercase__ : str ,lowercase__ : Optional[Any] ,lowercase__ : Optional[Any] ,lowercase__ : List[str] ,lowercase__ : Tuple ,lowercase__ : Tuple ,lowercase__ : Optional[int] ,lowercase__ : List[Any] ,): __lowercase = True __lowercase = NezhaModel(lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,encoder_hidden_states=lowercase__ ,encoder_attention_mask=lowercase__ ,) __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,encoder_hidden_states=lowercase__ ,) __lowercase = model(lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : List[str] ,lowercase__ : Dict ,lowercase__ : Tuple ,lowercase__ : Optional[Any] ,lowercase__ : List[Any] ,lowercase__ : List[Any] ,lowercase__ : Optional[Any] ): __lowercase = NezhaForMaskedLM(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model(lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : List[str] ,lowercase__ : Dict ,lowercase__ : Any ,lowercase__ : int ,lowercase__ : Union[str, Any] ,lowercase__ : Optional[int] ,lowercase__ : Any ): __lowercase = NezhaForNextSentencePrediction(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, 2) ) def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : str ,lowercase__ : Dict ,lowercase__ : Tuple ,lowercase__ : Dict ,lowercase__ : Tuple ,lowercase__ : int ,lowercase__ : int ): __lowercase = NezhaForPreTraining(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ,next_sentence_label=lowercase__ ,) self.parent.assertEqual(result.prediction_logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape ,(self.batch_size, 2) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : Union[str, Any] ,lowercase__ : Optional[Any] ,lowercase__ : Tuple ,lowercase__ : List[str] ,lowercase__ : Dict ,lowercase__ : Optional[int] ,lowercase__ : Union[str, Any] ): __lowercase = NezhaForQuestionAnswering(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,start_positions=lowercase__ ,end_positions=lowercase__ ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : Tuple ,lowercase__ : str ,lowercase__ : List[str] ,lowercase__ : Dict ,lowercase__ : Any ,lowercase__ : Optional[int] ,lowercase__ : int ): __lowercase = self.num_labels __lowercase = NezhaForSequenceClassification(lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model(lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : Union[str, Any] ,lowercase__ : List[str] ,lowercase__ : int ,lowercase__ : List[Any] ,lowercase__ : List[Any] ,lowercase__ : Any ,lowercase__ : Optional[Any] ): __lowercase = self.num_labels __lowercase = NezhaForTokenClassification(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model(lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : List[Any] ,lowercase__ : List[Any] ,lowercase__ : Optional[Any] ,lowercase__ : List[str] ,lowercase__ : Dict ,lowercase__ : List[Any] ,lowercase__ : str ): __lowercase = self.num_choices __lowercase = NezhaForMultipleChoice(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __lowercase = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __lowercase = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): __lowercase = self.prepare_config_and_inputs() ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = config_and_inputs __lowercase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowercase_ (lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE : Tuple = ( { 'feature-extraction': NezhaModel, 'fill-mask': NezhaForMaskedLM, 'question-answering': NezhaForQuestionAnswering, 'text-classification': NezhaForSequenceClassification, 'token-classification': NezhaForTokenClassification, 'zero-shot': NezhaForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE : List[str] = True def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : List[str] ,lowercase__ : str ,lowercase__ : Any=False ): __lowercase = super()._prepare_for_class(lowercase__ ,lowercase__ ,return_labels=lowercase__ ) if return_labels: if model_class in get_values(lowercase__ ): __lowercase = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) ,dtype=torch.long ,device=lowercase__ ) __lowercase = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=lowercase__ ) return inputs_dict def SCREAMING_SNAKE_CASE ( self : Tuple ): __lowercase = NezhaModelTester(self ) __lowercase = ConfigTester(self ,config_class=lowercase__ ,hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : int ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ): __lowercase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ): # This regression test was failing with PyTorch < 1.3 ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __lowercase = None self.model_tester.create_and_check_model_as_decoder( lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : str ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : str ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase__ ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase = NezhaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) @slow @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : Optional[int] ): __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __lowercase = True __lowercase = model_class(config=lowercase__ ) __lowercase = self._prepare_for_class(lowercase__ ,lowercase__ ) __lowercase = torch.jit.trace( lowercase__ ,(inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(lowercase__ ,os.path.join(lowercase__ ,'''bert.pt''' ) ) __lowercase = torch.jit.load(os.path.join(lowercase__ ,'''bert.pt''' ) ,map_location=lowercase__ ) loaded(inputs_dict['''input_ids'''].to(lowercase__ ) ,inputs_dict['''attention_mask'''].to(lowercase__ ) ) @require_torch class lowercase_ (unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = NezhaModel.from_pretrained('''sijunhe/nezha-cn-base''' ) __lowercase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __lowercase = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowercase = model(lowercase__ ,attention_mask=lowercase__ )[0] __lowercase = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape ,lowercase__ ) __lowercase = torch.tensor([[[0.0_6_8_5, 0.2_4_4_1, 0.1_1_0_2], [0.0_6_0_0, 0.1_9_0_6, 0.1_3_4_9], [0.0_2_2_1, 0.0_8_1_9, 0.0_5_8_6]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] ,lowercase__ ,atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE ( self : Dict ): __lowercase = NezhaForMaskedLM.from_pretrained('''sijunhe/nezha-cn-base''' ) __lowercase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __lowercase = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowercase = model(lowercase__ ,attention_mask=lowercase__ )[0] __lowercase = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape ,lowercase__ ) __lowercase = torch.tensor( [[-2.7_9_3_9, -1.7_9_0_2, -2.2_1_8_9], [-2.8_5_8_5, -1.8_9_0_8, -2.3_7_2_3], [-2.6_4_9_9, -1.7_7_5_0, -2.2_5_5_8]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] ,lowercase__ ,atol=1e-4 ) )
41
1
def __UpperCAmelCase ( __a : int = 50 ) -> int: """simple docstring""" _a : Union[str, Any] = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 ,5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'''{solution() = }''')
578
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) a__ = None a__ = { '''7B''': 11008, '''13B''': 13824, '''30B''': 17920, '''65B''': 22016, '''70B''': 28672, } a__ = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def __UpperCAmelCase ( __a : str ,__a : Optional[int]=1 ,__a : Any=256 ) -> Optional[Any]: """simple docstring""" return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def __UpperCAmelCase ( __a : Any ) -> Any: """simple docstring""" with open(__a ,'''r''' ) as f: return json.load(__a ) def __UpperCAmelCase ( __a : List[Any] ,__a : Any ) -> int: """simple docstring""" with open(__a ,'''w''' ) as f: json.dump(__a ,__a ) def __UpperCAmelCase ( __a : Optional[int] ,__a : Optional[Any] ,__a : int ,__a : Any=True ) -> Union[str, Any]: """simple docstring""" os.makedirs(__a ,exist_ok=__a ) _a : Optional[Any] = os.path.join(__a ,'''tmp''' ) os.makedirs(__a ,exist_ok=__a ) _a : Any = read_json(os.path.join(__a ,'''params.json''' ) ) _a : Optional[int] = NUM_SHARDS[model_size] _a : Optional[int] = params['''n_layers'''] _a : List[str] = params['''n_heads'''] _a : Union[str, Any] = n_heads // num_shards _a : str = params['''dim'''] _a : Optional[Any] = dim // n_heads _a : str = 1_00_00.0 _a : Union[str, Any] = 1.0 / (base ** (torch.arange(0 ,__a ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str = params['''n_kv_heads'''] # for GQA / MQA _a : Union[str, Any] = n_heads_per_shard // num_key_value_heads _a : List[str] = dim // num_key_value_heads else: # compatibility with other checkpoints _a : Optional[Any] = n_heads _a : Union[str, Any] = n_heads_per_shard _a : List[Any] = dim # permute for sliced rotary def permute(__a : Optional[Any] ,__a : Dict=n_heads ,__a : Dict=dim ,__a : Tuple=dim ): return w.view(__a ,dima // n_heads // 2 ,2 ,__a ).transpose(1 ,2 ).reshape(__a ,__a ) print(F"""Fetching all parameters from the checkpoint at {input_base_path}.""" ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _a : Any = torch.load(os.path.join(__a ,'''consolidated.00.pth''' ) ,map_location='''cpu''' ) else: # Sharded _a : Tuple = [ torch.load(os.path.join(__a ,F"""consolidated.{i:02d}.pth""" ) ,map_location='''cpu''' ) for i in range(__a ) ] _a : List[Any] = 0 _a : Optional[int] = {'''weight_map''': {}} for layer_i in range(__a ): _a : Any = F"""pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin""" if model_size == "7B": # Unsharded _a : List[str] = { F"""model.layers.{layer_i}.self_attn.q_proj.weight""": permute( loaded[F"""layers.{layer_i}.attention.wq.weight"""] ), F"""model.layers.{layer_i}.self_attn.k_proj.weight""": permute( loaded[F"""layers.{layer_i}.attention.wk.weight"""] ), F"""model.layers.{layer_i}.self_attn.v_proj.weight""": loaded[F"""layers.{layer_i}.attention.wv.weight"""], F"""model.layers.{layer_i}.self_attn.o_proj.weight""": loaded[F"""layers.{layer_i}.attention.wo.weight"""], F"""model.layers.{layer_i}.mlp.gate_proj.weight""": loaded[F"""layers.{layer_i}.feed_forward.w1.weight"""], F"""model.layers.{layer_i}.mlp.down_proj.weight""": loaded[F"""layers.{layer_i}.feed_forward.w2.weight"""], F"""model.layers.{layer_i}.mlp.up_proj.weight""": loaded[F"""layers.{layer_i}.feed_forward.w3.weight"""], F"""model.layers.{layer_i}.input_layernorm.weight""": loaded[F"""layers.{layer_i}.attention_norm.weight"""], F"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[F"""layers.{layer_i}.ffn_norm.weight"""], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _a : int = { F"""model.layers.{layer_i}.input_layernorm.weight""": loaded[0][ F"""layers.{layer_i}.attention_norm.weight""" ].clone(), F"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[0][ F"""layers.{layer_i}.ffn_norm.weight""" ].clone(), } _a : Optional[int] = permute( torch.cat( [ loaded[i][F"""layers.{layer_i}.attention.wq.weight"""].view(__a ,__a ,__a ) for i in range(__a ) ] ,dim=0 ,).reshape(__a ,__a ) ) _a : int = permute( torch.cat( [ loaded[i][F"""layers.{layer_i}.attention.wk.weight"""].view( __a ,__a ,__a ) for i in range(__a ) ] ,dim=0 ,).reshape(__a ,__a ) ,__a ,__a ,__a ,) _a : List[Any] = torch.cat( [ loaded[i][F"""layers.{layer_i}.attention.wv.weight"""].view( __a ,__a ,__a ) for i in range(__a ) ] ,dim=0 ,).reshape(__a ,__a ) _a : Dict = torch.cat( [loaded[i][F"""layers.{layer_i}.attention.wo.weight"""] for i in range(__a )] ,dim=1 ) _a : Optional[Any] = torch.cat( [loaded[i][F"""layers.{layer_i}.feed_forward.w1.weight"""] for i in range(__a )] ,dim=0 ) _a : str = torch.cat( [loaded[i][F"""layers.{layer_i}.feed_forward.w2.weight"""] for i in range(__a )] ,dim=1 ) _a : Dict = torch.cat( [loaded[i][F"""layers.{layer_i}.feed_forward.w3.weight"""] for i in range(__a )] ,dim=0 ) _a : Any = inv_freq for k, v in state_dict.items(): _a : Optional[int] = filename param_count += v.numel() torch.save(__a ,os.path.join(__a ,__a ) ) _a : int = F"""pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin""" if model_size == "7B": # Unsharded _a : int = { '''model.embed_tokens.weight''': loaded['''tok_embeddings.weight'''], '''model.norm.weight''': loaded['''norm.weight'''], '''lm_head.weight''': loaded['''output.weight'''], } else: _a : List[str] = { '''model.norm.weight''': loaded[0]['''norm.weight'''], '''model.embed_tokens.weight''': torch.cat( [loaded[i]['''tok_embeddings.weight'''] for i in range(__a )] ,dim=1 ), '''lm_head.weight''': torch.cat([loaded[i]['''output.weight'''] for i in range(__a )] ,dim=0 ), } for k, v in state_dict.items(): _a : Any = filename param_count += v.numel() torch.save(__a ,os.path.join(__a ,__a ) ) # Write configs _a : Tuple = {'''total_size''': param_count * 2} write_json(__a ,os.path.join(__a ,'''pytorch_model.bin.index.json''' ) ) _a : Any = params['''ffn_dim_multiplier'''] if '''ffn_dim_multiplier''' in params else 1 _a : int = params['''multiple_of'''] if '''multiple_of''' in params else 256 _a : Union[str, Any] = LlamaConfig( hidden_size=__a ,intermediate_size=compute_intermediate_size(__a ,__a ,__a ) ,num_attention_heads=params['''n_heads'''] ,num_hidden_layers=params['''n_layers'''] ,rms_norm_eps=params['''norm_eps'''] ,num_key_value_heads=__a ,) config.save_pretrained(__a ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print('''Loading the checkpoint in a Llama model.''' ) _a : Optional[Any] = LlamaForCausalLM.from_pretrained(__a ,torch_dtype=torch.floataa ,low_cpu_mem_usage=__a ) # Avoid saving this as part of the config. del model.config._name_or_path print('''Saving in the Transformers format.''' ) model.save_pretrained(__a ,safe_serialization=__a ) shutil.rmtree(__a ) def __UpperCAmelCase ( __a : Tuple ,__a : List[Any] ) -> int: """simple docstring""" _a : Optional[int] = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"""Saving a {tokenizer_class.__name__} to {tokenizer_path}.""" ) _a : List[Any] = tokenizer_class(__a ) tokenizer.save_pretrained(__a ) def __UpperCAmelCase ( ) -> List[str]: """simple docstring""" _a : Dict = argparse.ArgumentParser() parser.add_argument( '''--input_dir''' ,help='''Location of LLaMA weights, which contains tokenizer.model and model folders''' ,) parser.add_argument( '''--model_size''' ,choices=['''7B''', '''7Bf''', '''13B''', '''13Bf''', '''30B''', '''65B''', '''70B''', '''70Bf''', '''tokenizer_only'''] ,) parser.add_argument( '''--output_dir''' ,help='''Location to write HF model and tokenizer''' ,) parser.add_argument('''--safe_serialization''' ,type=__a ,help='''Whether or not to save using `safetensors`.''' ) _a : List[Any] = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir ,input_base_path=os.path.join(args.input_dir ,args.model_size ) ,model_size=args.model_size ,safe_serialization=args.safe_serialization ,) _a : List[Any] = os.path.join(args.input_dir ,'''tokenizer.model''' ) write_tokenizer(args.output_dir ,__a ) if __name__ == "__main__": main()
578
1
'''simple docstring''' from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def _lowercase (SCREAMING_SNAKE_CASE ): '''simple docstring''' def is_in_circle(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> bool: __A : Tuple = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle __A : Union[str, Any] = mean( int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) ) for _ in range(SCREAMING_SNAKE_CASE ) ) # The ratio of the area for circle to square is pi/4. __A : List[Any] = proportion * 4 print(f"The estimated value of pi is {pi_estimate}" ) print(f"The numpy value of pi is {pi}" ) print(f"The total error is {abs(pi - pi_estimate )}" ) def _lowercase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = 1.0 , ): '''simple docstring''' return mean( function_to_integrate(uniform(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) for _ in range(SCREAMING_SNAKE_CASE ) ) * (max_value - min_value) def _lowercase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = 1.0 ): '''simple docstring''' def identity_function(SCREAMING_SNAKE_CASE ) -> float: return x __A : Tuple = area_under_curve_estimator( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __A : str = (max_value * max_value - min_value * min_value) / 2 print("******************" ) print(f"Estimating area under y=x where x varies from {min_value} to {max_value}" ) print(f"Estimated value is {estimated_value}" ) print(f"Expected value is {expected_value}" ) print(f"Total error is {abs(estimated_value - expected_value )}" ) print("******************" ) def _lowercase (SCREAMING_SNAKE_CASE ): '''simple docstring''' def function_to_integrate(SCREAMING_SNAKE_CASE ) -> float: return sqrt(4.0 - x * x ) __A : Dict = area_under_curve_estimator( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 0.0 , 2.0 ) print("******************" ) print("Estimating pi using area_under_curve_estimator" ) print(f"Estimated value is {estimated_value}" ) print(f"Expected value is {pi}" ) print(f"Total error is {abs(estimated_value - pi )}" ) print("******************" ) if __name__ == "__main__": import doctest doctest.testmod()
111
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _UpperCamelCase = 16 _UpperCamelCase = 32 def _lowercase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 16 ): '''simple docstring''' __A : Tuple = AutoTokenizer.from_pretrained("bert-base-cased" ) __A : List[str] = load_dataset("glue" , "mrpc" ) def tokenize_function(SCREAMING_SNAKE_CASE ): # max_length=None => use the model max length (it's actually the default) __A : Any = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __A : Optional[Any] = datasets.map( SCREAMING_SNAKE_CASE , batched=SCREAMING_SNAKE_CASE , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __A : List[Any] = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(SCREAMING_SNAKE_CASE ): # On TPU it's best to pad everything to the same length or training will be very slow. __A : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __A : List[str] = 16 elif accelerator.mixed_precision != "no": __A : Tuple = 8 else: __A : Optional[Any] = None return tokenizer.pad( SCREAMING_SNAKE_CASE , padding="longest" , max_length=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_tensors="pt" , ) # Instantiate dataloaders. __A : Optional[int] = DataLoader( tokenized_datasets["train"] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE ) __A : Tuple = DataLoader( tokenized_datasets["validation"] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders _UpperCamelCase = mocked_dataloaders # noqa: F811 def _lowercase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , SCREAMING_SNAKE_CASE ) == "1": __A : int = 2 # New Code # __A : List[str] = int(args.gradient_accumulation_steps ) __A : int = int(args.local_sgd_steps ) # Initialize accelerator __A : int = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=SCREAMING_SNAKE_CASE ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __A : Tuple = config["lr"] __A : Union[str, Any] = int(config["num_epochs"] ) __A : Optional[int] = int(config["seed"] ) __A : Optional[Any] = int(config["batch_size"] ) __A : Optional[int] = evaluate.load("glue" , "mrpc" ) set_seed(SCREAMING_SNAKE_CASE ) __A ,__A : Tuple = get_dataloaders(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __A : List[str] = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=SCREAMING_SNAKE_CASE ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __A : Union[str, Any] = model.to(accelerator.device ) # Instantiate optimizer __A : str = AdamW(params=model.parameters() , lr=SCREAMING_SNAKE_CASE ) # Instantiate scheduler __A : Optional[int] = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(SCREAMING_SNAKE_CASE ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __A ,__A ,__A ,__A ,__A : List[str] = accelerator.prepare( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Now we train the model for epoch in range(SCREAMING_SNAKE_CASE ): model.train() with LocalSGD( accelerator=SCREAMING_SNAKE_CASE , model=SCREAMING_SNAKE_CASE , local_sgd_steps=SCREAMING_SNAKE_CASE , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(SCREAMING_SNAKE_CASE ): __A : List[Any] = model(**SCREAMING_SNAKE_CASE ) __A : List[str] = output.loss accelerator.backward(SCREAMING_SNAKE_CASE ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __A : Tuple = model(**SCREAMING_SNAKE_CASE ) __A : Union[str, Any] = outputs.logits.argmax(dim=-1 ) __A ,__A : Tuple = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=SCREAMING_SNAKE_CASE , references=SCREAMING_SNAKE_CASE , ) __A : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , SCREAMING_SNAKE_CASE ) def _lowercase (): '''simple docstring''' __A : Dict = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) # New Code # parser.add_argument( "--gradient_accumulation_steps" , type=SCREAMING_SNAKE_CASE , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument( "--local_sgd_steps" , type=SCREAMING_SNAKE_CASE , default=8 , help="Number of local SGD steps or None to disable local SGD" ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) __A : List[str] = parser.parse_args() __A : List[str] = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
111
1
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class SCREAMING_SNAKE_CASE__ ( __UpperCamelCase ): @staticmethod @abstractmethod def __lowerCamelCase ( __UpperCamelCase ): '''simple docstring''' raise NotImplementedError() @abstractmethod def __lowerCamelCase ( self ): '''simple docstring''' raise NotImplementedError()
716
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Any = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.linear_k': 'encoder.layers.*.self_attn.linear_k', 'self_attn.linear_v': 'encoder.layers.*.self_attn.linear_v', 'self_attn.linear_q': 'encoder.layers.*.self_attn.linear_q', 'self_attn.pos_bias_u': 'encoder.layers.*.self_attn.pos_bias_u', 'self_attn.pos_bias_v': 'encoder.layers.*.self_attn.pos_bias_v', 'self_attn.linear_out': 'encoder.layers.*.self_attn.linear_out', 'self_attn.linear_pos': 'encoder.layers.*.self_attn.linear_pos', 'self_attn.rotary_emb': 'encoder.embed_positions', 'self_attn_layer_norm': 'encoder.layers.*.self_attn_layer_norm', 'conv_module.pointwise_conv1': 'encoder.layers.*.conv_module.pointwise_conv1', 'conv_module.pointwise_conv2': 'encoder.layers.*.conv_module.pointwise_conv2', 'conv_module.depthwise_conv': 'encoder.layers.*.conv_module.depthwise_conv', 'conv_module.batch_norm': 'encoder.layers.*.conv_module.batch_norm', 'conv_module.layer_norm': 'encoder.layers.*.conv_module.layer_norm', 'ffn1.w_1': 'encoder.layers.*.ffn1.intermediate_dense', 'ffn1.w_2': 'encoder.layers.*.ffn1.output_dense', 'ffn1.layer_norm': 'encoder.layers.*.ffn1_layer_norm', 'ffn2.w_1': 'encoder.layers.*.ffn2.intermediate_dense', 'ffn2.w_2': 'encoder.layers.*.ffn2.output_dense', 'ffn2.layer_norm': 'encoder.layers.*.ffn2_layer_norm', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def _snake_case ( lowercase , lowercase , lowercase , lowercase , lowercase ) -> List[Any]: for attribute in key.split(""".""" ): __a : str = getattr(lowercase , lowercase ) if weight_type is not None: __a : Dict = getattr(lowercase , lowercase ).shape else: __a : Dict = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __a : Any = value elif weight_type == "weight_g": __a : int = value elif weight_type == "weight_v": __a : int = value elif weight_type == "bias": __a : List[Any] = value elif weight_type == "running_mean": __a : Union[str, Any] = value elif weight_type == "running_var": __a : Tuple = value elif weight_type == "num_batches_tracked": __a : Optional[int] = value elif weight_type == "inv_freq": __a : List[str] = value else: __a : List[str] = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _snake_case ( lowercase , lowercase , lowercase ) -> Dict: __a : Dict = [] __a : Dict = fairseq_model.state_dict() __a : Tuple = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __a : int = False if "conv_layers" in name: load_conv_layer( lowercase , lowercase , lowercase , lowercase , hf_model.config.feat_extract_norm == """group""" , ) __a : List[Any] = True else: for key, mapped_key in MAPPING.items(): __a : Optional[int] = """wav2vec2_conformer.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __a : str = True if "*" in mapped_key: __a : Optional[int] = name.split(lowercase )[0].split(""".""" )[-2] __a : List[Any] = mapped_key.replace("""*""" , lowercase ) if "pos_bias_u" in name: __a : Union[str, Any] = None elif "pos_bias_v" in name: __a : List[Any] = None elif "weight_g" in name: __a : List[Any] = """weight_g""" elif "weight_v" in name: __a : List[Any] = """weight_v""" elif "bias" in name: __a : Optional[int] = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj __a : str = """weight""" elif "running_mean" in name: __a : List[str] = """running_mean""" elif "inv_freq" in name: __a : Dict = """inv_freq""" elif "running_var" in name: __a : Union[str, Any] = """running_var""" elif "num_batches_tracked" in name: __a : int = """num_batches_tracked""" else: __a : Optional[int] = None set_recursively(lowercase , lowercase , lowercase , lowercase , lowercase ) continue if not is_used: unused_weights.append(lowercase ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _snake_case ( lowercase , lowercase , lowercase , lowercase , lowercase ) -> List[str]: __a : Optional[Any] = full_name.split("""conv_layers.""" )[-1] __a : Union[str, Any] = name.split(""".""" ) __a : Optional[Any] = int(items[0] ) __a : int = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __a : Dict = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __a : str = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __a : Dict = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __a : Union[str, Any] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(lowercase ) @torch.no_grad() def _snake_case ( lowercase , lowercase , lowercase=None , lowercase=None , lowercase=True ) -> Optional[Any]: if config_path is not None: __a : Any = WavaVecaConformerConfig.from_pretrained(lowercase , hidden_act="""swish""" ) else: __a : Optional[int] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __a : Optional[Any] = """rotary""" if is_finetuned: if dict_path: __a : List[Any] = Dictionary.load(lowercase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __a : int = target_dict.pad_index __a : List[str] = target_dict.bos_index __a : str = target_dict.eos_index __a : Dict = len(target_dict.symbols ) __a : Any = os.path.join(lowercase , """vocab.json""" ) if not os.path.isdir(lowercase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(lowercase ) ) return os.makedirs(lowercase , exist_ok=lowercase ) __a : Dict = target_dict.indices # fairseq has the <pad> and <s> switched __a : Optional[Any] = 0 __a : List[Any] = 1 with open(lowercase , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(lowercase , lowercase ) __a : int = WavaVecaCTCTokenizer( lowercase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=lowercase , ) __a : Optional[int] = True if config.feat_extract_norm == """layer""" else False __a : Dict = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=lowercase , return_attention_mask=lowercase , ) __a : str = WavaVecaProcessor(feature_extractor=lowercase , tokenizer=lowercase ) processor.save_pretrained(lowercase ) __a : List[str] = WavaVecaConformerForCTC(lowercase ) else: __a : Optional[int] = WavaVecaConformerForPreTraining(lowercase ) if is_finetuned: __a , __a , __a : Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: __a : Optional[int] = argparse.Namespace(task="""audio_pretraining""" ) __a : Tuple = fairseq.tasks.setup_task(lowercase ) __a , __a , __a : int = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=lowercase ) __a : Any = model[0].eval() recursively_load_weights(lowercase , lowercase , not is_finetuned ) hf_wavavec.save_pretrained(lowercase ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Dict = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
697
0
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) class __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" def __init__( self : Dict , *_snake_case : int , **_snake_case : Optional[int] ): """simple docstring""" warnings.warn( 'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use CLIPImageProcessor instead.' , _snake_case , ) super().__init__(*_snake_case , **_snake_case )
9
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.layoutlm.modeling_tf_layoutlm import ( TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMForMaskedLM, TFLayoutLMForQuestionAnswering, TFLayoutLMForSequenceClassification, TFLayoutLMForTokenClassification, TFLayoutLMModel, ) class a : def __init__( self , _snake_case , _snake_case=13 , _snake_case=7 , _snake_case=True , _snake_case=True , _snake_case=True , _snake_case=True , _snake_case=99 , _snake_case=32 , _snake_case=2 , _snake_case=4 , _snake_case=37 , _snake_case="gelu" , _snake_case=0.1 , _snake_case=0.1 , _snake_case=5_12 , _snake_case=16 , _snake_case=2 , _snake_case=0.02 , _snake_case=3 , _snake_case=4 , _snake_case=None , _snake_case=10_00 , ): """simple docstring""" lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = seq_length lowerCAmelCase = is_training lowerCAmelCase = use_input_mask lowerCAmelCase = use_token_type_ids lowerCAmelCase = use_labels lowerCAmelCase = vocab_size lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_act lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = max_position_embeddings lowerCAmelCase = type_vocab_size lowerCAmelCase = type_sequence_label_size lowerCAmelCase = initializer_range lowerCAmelCase = num_labels lowerCAmelCase = num_choices lowerCAmelCase = scope lowerCAmelCase = range_bbox def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # convert bbox to numpy since TF does not support item assignment lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ).numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: lowerCAmelCase = bbox[i, j, 3] lowerCAmelCase = bbox[i, j, 1] lowerCAmelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: lowerCAmelCase = bbox[i, j, 2] lowerCAmelCase = bbox[i, j, 0] lowerCAmelCase = t lowerCAmelCase = tf.convert_to_tensor(_snake_case ) lowerCAmelCase = None if self.use_input_mask: lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase = None if self.use_token_type_ids: lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase = None lowerCAmelCase = None lowerCAmelCase = None if self.use_labels: lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase = LayoutLMConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" lowerCAmelCase = TFLayoutLMModel(config=_snake_case ) lowerCAmelCase = model(_snake_case , _snake_case , attention_mask=_snake_case , token_type_ids=_snake_case ) lowerCAmelCase = model(_snake_case , _snake_case , token_type_ids=_snake_case ) lowerCAmelCase = model(_snake_case , _snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" lowerCAmelCase = TFLayoutLMForMaskedLM(config=_snake_case ) lowerCAmelCase = model(_snake_case , _snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=_snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" lowerCAmelCase = self.num_labels lowerCAmelCase = TFLayoutLMForSequenceClassification(config=_snake_case ) lowerCAmelCase = model(_snake_case , _snake_case , attention_mask=_snake_case , token_type_ids=_snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" lowerCAmelCase = self.num_labels lowerCAmelCase = TFLayoutLMForTokenClassification(config=_snake_case ) lowerCAmelCase = model(_snake_case , _snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=_snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" lowerCAmelCase = TFLayoutLMForQuestionAnswering(config=_snake_case ) lowerCAmelCase = model(_snake_case , _snake_case , attention_mask=_snake_case , token_type_ids=_snake_case ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.prepare_config_and_inputs() ( ( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) ,( lowerCAmelCase ) , ) = config_and_inputs lowerCAmelCase = { 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class a ( a__ , a__ , unittest.TestCase ): snake_case__ = ( ( TFLayoutLMModel, TFLayoutLMForMaskedLM, TFLayoutLMForTokenClassification, TFLayoutLMForSequenceClassification, TFLayoutLMForQuestionAnswering, ) if is_tf_available() else () ) snake_case__ = ( { '''feature-extraction''': TFLayoutLMModel, '''fill-mask''': TFLayoutLMForMaskedLM, '''text-classification''': TFLayoutLMForSequenceClassification, '''token-classification''': TFLayoutLMForTokenClassification, '''zero-shot''': TFLayoutLMForSequenceClassification, } if is_tf_available() else {} ) snake_case__ = False snake_case__ = True snake_case__ = 1_0 def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = TFLayoutLMModelTester(self ) lowerCAmelCase = ConfigTester(self , config_class=_snake_case , hidden_size=37 ) def UpperCamelCase__ ( self ): """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_snake_case ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_snake_case ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_snake_case ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_snake_case ) @slow def UpperCamelCase__ ( self ): """simple docstring""" for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase = TFLayoutLMModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) @unittest.skip('Onnx compliancy broke with TF 2.10' ) def UpperCamelCase__ ( self ): """simple docstring""" pass def _SCREAMING_SNAKE_CASE (): # Here we prepare a batch of 2 sequences to test a LayoutLM forward pass on: # fmt: off lowerCAmelCase = tf.convert_to_tensor([[101,1019,1014,1016,1037,1_2849,4747,1004,1_4246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,1_1300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,1_9274,2772,6205,2_7814,1_6147,1_6147,4343,2047,1_0283,1_0969,1_4389,1012,2338,102]] ) # noqa: E231 lowerCAmelCase = tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],] ) # noqa: E231 lowerCAmelCase = tf.convert_to_tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1000,1000,1000,1000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1000,1000,1000,1000]]] ) # noqa: E231 lowerCAmelCase = tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] ) # noqa: E231 # these are sequence labels (i.e. at the token level) lowerCAmelCase = tf.convert_to_tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]] ) # noqa: E231 # fmt: on return input_ids, attention_mask, bbox, token_type_ids, labels @require_tf class a ( unittest.TestCase ): @slow def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = TFLayoutLMModel.from_pretrained('microsoft/layoutlm-base-uncased' ) lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase = prepare_layoutlm_batch_inputs() # forward pass lowerCAmelCase = model(input_ids=_snake_case , bbox=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case ) # test the sequence output on [0, :3, :3] lowerCAmelCase = tf.convert_to_tensor( [[0.1_785, -0.1_947, -0.0_425], [-0.3_254, -0.2_807, 0.2_553], [-0.5_391, -0.3_322, 0.3_364]] , ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , _snake_case , atol=1E-3 ) ) # test the pooled output on [1, :3] lowerCAmelCase = tf.convert_to_tensor([-0.6_580, -0.0_214, 0.8_552] ) self.assertTrue(np.allclose(outputs.pooler_output[1, :3] , _snake_case , atol=1E-3 ) ) @slow def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = TFLayoutLMForSequenceClassification.from_pretrained('microsoft/layoutlm-base-uncased' , num_labels=2 ) lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase = prepare_layoutlm_batch_inputs() # forward pass lowerCAmelCase = model( input_ids=_snake_case , bbox=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=tf.convert_to_tensor([1, 1] ) , ) # test whether we get a loss as a scalar lowerCAmelCase = outputs.loss lowerCAmelCase = (2,) self.assertEqual(loss.shape , _snake_case ) # test the shape of the logits lowerCAmelCase = outputs.logits lowerCAmelCase = (2, 2) self.assertEqual(logits.shape , _snake_case ) @slow def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = TFLayoutLMForTokenClassification.from_pretrained('microsoft/layoutlm-base-uncased' , num_labels=13 ) lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase = prepare_layoutlm_batch_inputs() # forward pass lowerCAmelCase = model( input_ids=_snake_case , bbox=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=_snake_case ) # test the shape of the logits lowerCAmelCase = outputs.logits lowerCAmelCase = tf.convert_to_tensor((2, 25, 13) ) self.assertEqual(logits.shape , _snake_case ) @slow def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = TFLayoutLMForQuestionAnswering.from_pretrained('microsoft/layoutlm-base-uncased' ) lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase ,lowerCAmelCase = prepare_layoutlm_batch_inputs() # forward pass lowerCAmelCase = model(input_ids=_snake_case , bbox=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case ) # test the shape of the logits lowerCAmelCase = tf.convert_to_tensor((2, 25) ) self.assertEqual(outputs.start_logits.shape , _snake_case ) self.assertEqual(outputs.end_logits.shape , _snake_case )
4
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowercase = { 'configuration_transfo_xl': ['TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TransfoXLConfig'], 'tokenization_transfo_xl': ['TransfoXLCorpus', 'TransfoXLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ 'TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'AdaptiveEmbedding', 'TransfoXLForSequenceClassification', 'TransfoXLLMHeadModel', 'TransfoXLModel', 'TransfoXLPreTrainedModel', 'load_tf_weights_in_transfo_xl', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ 'TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFAdaptiveEmbedding', 'TFTransfoXLForSequenceClassification', 'TFTransfoXLLMHeadModel', 'TFTransfoXLMainLayer', 'TFTransfoXLModel', 'TFTransfoXLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_transfo_xl import ( TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, AdaptiveEmbedding, TransfoXLForSequenceClassification, TransfoXLLMHeadModel, TransfoXLModel, TransfoXLPreTrainedModel, load_tf_weights_in_transfo_xl, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_transfo_xl import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFAdaptiveEmbedding, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLMainLayer, TFTransfoXLModel, TFTransfoXLPreTrainedModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
708
'''simple docstring''' import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path _lowercase = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def __UpperCamelCase ( a : Dict=True ) ->str: if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=__a ) ) class _lowercase ( __a ): _UpperCAmelCase = None _UpperCAmelCase = None def UpperCamelCase ( self , A__ , A__ ) -> str: with TemporaryDirectory() as tmp_dir: snake_case = dataset_module_factory(A__ , cache_dir=A__ ) snake_case = import_main_class(dataset_module.module_path , dataset=A__ ) snake_case = builder_cls( cache_dir=A__ , config_name=A__ , hash=dataset_module.hash , ) snake_case = '''/'''.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=A__ ).replace(os.sep , '''/''' ), config.DATASET_INFO_FILENAME, ] ) snake_case = cached_path(A__ , cache_dir=A__ ) self.assertTrue(os.path.exists(A__ ) ) @pytest.mark.integration def __UpperCamelCase ( a : List[str] ) ->Any: snake_case = tmp_path_factory.mktemp('''test_hf_gcp''' ) / '''test_wikipedia_simple''' snake_case = dataset_module_factory('''wikipedia''' , cache_dir=a ) snake_case = import_main_class(dataset_module.module_path ) snake_case = builder_cls( cache_dir=a , config_name='''20220301.frr''' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam snake_case = None builder_instance.download_and_prepare() snake_case = builder_instance.as_dataset() assert ds @pytest.mark.integration def __UpperCamelCase ( a : Any ) ->Union[str, Any]: snake_case = dataset_module_factory('''wikipedia''' , cache_dir=a ) snake_case = import_main_class(dataset_module.module_path , dataset=a ) snake_case = builder_cls( cache_dir=a , config_name='''20220301.frr''' , hash=dataset_module.hash , ) snake_case = builder_instance.as_streaming_dataset() assert ds assert isinstance(a , a ) assert "train" in ds assert isinstance(ds['''train'''] , a ) assert next(iter(ds['''train'''] ) )
44
0
'''simple docstring''' import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__=None ) -> int: 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(UpperCAmelCase__, headers=UpperCAmelCase__ ).json() A_ = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) A_ = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(UpperCAmelCase__ ): A_ = requests.get(url + F'''&page={i + 2}''', headers=UpperCAmelCase__ ).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 UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__=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(UpperCAmelCase__, headers=UpperCAmelCase__ ).json() A_ = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) A_ = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(UpperCAmelCase__ ): A_ = requests.get(url + F'''&page={i + 2}''', headers=UpperCAmelCase__ ).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 UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) -> Optional[Any]: A_ = None if token is not None: A_ = {"""Accept""": """application/vnd.github+json""", """Authorization""": F'''Bearer {token}'''} A_ = requests.get(UpperCAmelCase__, headers=UpperCAmelCase__, allow_redirects=UpperCAmelCase__ ) A_ = result.headers["""Location"""] A_ = requests.get(UpperCAmelCase__, allow_redirects=UpperCAmelCase__ ) A_ = os.path.join(UpperCAmelCase__, F'''{artifact_name}.zip''' ) with open(UpperCAmelCase__, """wb""" ) as fp: fp.write(response.content ) def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__=None ) -> Optional[int]: A_ = [] A_ = [] A_ = None with zipfile.ZipFile(UpperCAmelCase__ ) as z: for filename in z.namelist(): if not os.path.isdir(UpperCAmelCase__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(UpperCAmelCase__ ) 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(UpperCAmelCase__ ) elif filename == "job_name.txt": A_ = line if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ): raise ValueError( F'''`errors` and `failed_tests` should have the same number of elements. Got {len(UpperCAmelCase__ )} for `errors` ''' F'''and {len(UpperCAmelCase__ )} 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(UpperCAmelCase__, UpperCAmelCase__ ) # A list with elements of the form (line of error, error, failed test) A_ = [x + [y] + [job_link] for x, y in zip(UpperCAmelCase__, UpperCAmelCase__ )] return result def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__=None ) -> str: A_ = [] A_ = [os.path.join(UpperCAmelCase__, UpperCAmelCase__ ) for p in os.listdir(UpperCAmelCase__ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(UpperCAmelCase__, job_links=UpperCAmelCase__ ) ) return errors def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__=None ) -> int: 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 UpperCAmelCase__ : item[1]["count"], reverse=UpperCAmelCase__ ) ) return r def UpperCAmelCase__ ( UpperCAmelCase__ ) -> str: A_ = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): A_ = test.split("""/""" )[2] else: A_ = None return test def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__=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 UpperCAmelCase__ : item[1]["count"], reverse=UpperCAmelCase__ ) ) return r def UpperCAmelCase__ ( UpperCAmelCase__ ) -> Union[str, Any]: A_ = """| no. | error | status |""" A_ = """|-:|:-|:-|""" A_ = [header, sep] for error in reduced_by_error: A_ = reduced_by_error[error]["""count"""] A_ = F'''| {count} | {error[:1_00]} | |''' lines.append(UpperCAmelCase__ ) return "\n".join(UpperCAmelCase__ ) def UpperCAmelCase__ ( UpperCAmelCase__ ) -> str: 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(UpperCAmelCase__ ) return "\n".join(UpperCAmelCase__ ) if __name__ == "__main__": __lowerCamelCase = 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.''') __lowerCamelCase = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) __lowerCamelCase = get_job_links(args.workflow_run_id, token=args.token) __lowerCamelCase = {} # 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: __lowerCamelCase = k.find(''' / ''') __lowerCamelCase = k[index + len(''' / ''') :] __lowerCamelCase = 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) __lowerCamelCase = 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) __lowerCamelCase = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error __lowerCamelCase = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors __lowerCamelCase = counter.most_common(30) 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) __lowerCamelCase = reduce_by_error(errors) __lowerCamelCase = reduce_by_model(errors) __lowerCamelCase = make_github_table(reduced_by_error) __lowerCamelCase = 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)
288
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCamelCase = { '''configuration_whisper''': ['''WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''WhisperConfig''', '''WhisperOnnxConfig'''], '''feature_extraction_whisper''': ['''WhisperFeatureExtractor'''], '''processing_whisper''': ['''WhisperProcessor'''], '''tokenization_whisper''': ['''WhisperTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = ['''WhisperTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ '''WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''WhisperForConditionalGeneration''', '''WhisperModel''', '''WhisperPreTrainedModel''', '''WhisperForAudioClassification''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ '''TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFWhisperForConditionalGeneration''', '''TFWhisperModel''', '''TFWhisperPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ '''FlaxWhisperForConditionalGeneration''', '''FlaxWhisperModel''', '''FlaxWhisperPreTrainedModel''', '''FlaxWhisperForAudioClassification''', ] if TYPE_CHECKING: from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig from .feature_extraction_whisper import WhisperFeatureExtractor from .processing_whisper import WhisperProcessor from .tokenization_whisper import WhisperTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_whisper_fast import WhisperTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_whisper import ( WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, WhisperForAudioClassification, WhisperForConditionalGeneration, WhisperModel, WhisperPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_whisper import ( TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, TFWhisperForConditionalGeneration, TFWhisperModel, TFWhisperPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_whisper import ( FlaxWhisperForAudioClassification, FlaxWhisperForConditionalGeneration, FlaxWhisperModel, FlaxWhisperPreTrainedModel, ) else: import sys __lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
288
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_owlvit import OwlViTImageProcessor UpperCamelCase : Tuple = logging.get_logger(__name__) class lowerCamelCase__ ( UpperCAmelCase_ ): def __init__( self : Any , *_lowercase : Tuple , **_lowercase : Tuple ): warnings.warn( 'The class OwlViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use OwlViTImageProcessor instead.' , _lowercase , ) super().__init__(*_lowercase , **_lowercase )
719
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase : Dict = { "configuration_megatron_bert": ["MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegatronBertConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase : Any = [ "MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "MegatronBertForCausalLM", "MegatronBertForMaskedLM", "MegatronBertForMultipleChoice", "MegatronBertForNextSentencePrediction", "MegatronBertForPreTraining", "MegatronBertForQuestionAnswering", "MegatronBertForSequenceClassification", "MegatronBertForTokenClassification", "MegatronBertModel", "MegatronBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys UpperCamelCase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
91
0
'''simple docstring''' import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) SCREAMING_SNAKE_CASE__ : Optional[int] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class a__: a_ : str = field( default=snake_case__ , metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(snake_case__ )} ) a_ : str = field( default=snake_case__ , metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''} ) a_ : int = field( default=1_2_8 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) a_ : int = field( default=1_2_8 , metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''} , ) a_ : int = field( default=6_4 , metadata={ '''help''': ( '''The maximum number of tokens for the question. Questions longer than this will ''' '''be truncated to this length.''' ) } , ) a_ : int = field( default=3_0 , metadata={ '''help''': ( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ) } , ) a_ : bool = field( default=snake_case__ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) a_ : bool = field( default=snake_case__ , metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''} ) a_ : float = field( default=0.0 , metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''} ) a_ : int = field( default=2_0 , metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''} ) a_ : int = field( default=0 , metadata={ '''help''': ( '''language id of input for language-specific xlm models (see''' ''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)''' ) } , ) a_ : int = field(default=1 , metadata={'''help''': '''multiple threads for converting example to features'''} ) class a__( snake_case__ ): a_ : Optional[int] = '''train''' a_ : Optional[int] = '''dev''' class a__( snake_case__ ): a_ : SquadDataTrainingArguments a_ : List[SquadFeatures] a_ : Split a_ : bool def __init__( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = Split.train , _UpperCAmelCase = False , _UpperCAmelCase = None , _UpperCAmelCase = "pt" , ) -> Any: snake_case__ =args snake_case__ =is_language_sensitive snake_case__ =SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(_UpperCAmelCase , _UpperCAmelCase ): try: snake_case__ =Split[mode] except KeyError: raise KeyError('mode is not a valid split name' ) snake_case__ =mode # Load data features from cache or dataset file snake_case__ ='v2' if args.version_2_with_negative else 'v1' snake_case__ =os.path.join( cache_dir if cache_dir is not None else args.data_dir , f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}""" , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case__ =cached_features_file + '.lock' with FileLock(_UpperCAmelCase ): if os.path.exists(_UpperCAmelCase ) and not args.overwrite_cache: snake_case__ =time.time() snake_case__ =torch.load(_UpperCAmelCase ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. snake_case__ =self.old_features['features'] snake_case__ =self.old_features.get('dataset' , _UpperCAmelCase ) snake_case__ =self.old_features.get('examples' , _UpperCAmelCase ) logger.info( f"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( f"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in""" ' future run' ) else: if mode == Split.dev: snake_case__ =self.processor.get_dev_examples(args.data_dir ) else: snake_case__ =self.processor.get_train_examples(args.data_dir ) snake_case__ , snake_case__ =squad_convert_examples_to_features( examples=self.examples , tokenizer=_UpperCAmelCase , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=_UpperCAmelCase , ) snake_case__ =time.time() torch.save( {'features': self.features, 'dataset': self.dataset, 'examples': self.examples} , _UpperCAmelCase , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" ) def __len__( self ) -> Optional[int]: return len(self.features ) def __getitem__( self , _UpperCAmelCase ) -> Dict[str, torch.Tensor]: # Convert to Tensors and build dataset snake_case__ =self.features[i] snake_case__ =torch.tensor(feature.input_ids , dtype=torch.long ) snake_case__ =torch.tensor(feature.attention_mask , dtype=torch.long ) snake_case__ =torch.tensor(feature.token_type_ids , dtype=torch.long ) snake_case__ =torch.tensor(feature.cls_index , dtype=torch.long ) snake_case__ =torch.tensor(feature.p_mask , dtype=torch.float ) snake_case__ =torch.tensor(feature.is_impossible , dtype=torch.float ) snake_case__ ={ 'input_ids': input_ids, 'attention_mask': attention_mask, 'token_type_ids': token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({'cls_index': cls_index, 'p_mask': p_mask} ) if self.args.version_2_with_negative: inputs.update({'is_impossible': is_impossible} ) if self.is_language_sensitive: inputs.update({'langs': (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: snake_case__ =torch.tensor(feature.start_position , dtype=torch.long ) snake_case__ =torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({'start_positions': start_positions, 'end_positions': end_positions} ) return inputs
538
'''simple docstring''' import collections import os import re from pathlib import Path SCREAMING_SNAKE_CASE__ : List[Any] = '''src/transformers''' # Matches is_xxx_available() SCREAMING_SNAKE_CASE__ : List[str] = re.compile(r'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} SCREAMING_SNAKE_CASE__ : Optional[Any] = re.compile(r'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] SCREAMING_SNAKE_CASE__ : List[str] = re.compile(r'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available SCREAMING_SNAKE_CASE__ : List[str] = re.compile(r'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] SCREAMING_SNAKE_CASE__ : Tuple = re.compile(r'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", SCREAMING_SNAKE_CASE__ : Any = re.compile(r'''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], SCREAMING_SNAKE_CASE__ : List[Any] = re.compile(r'''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo SCREAMING_SNAKE_CASE__ : Optional[int] = re.compile(r'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: SCREAMING_SNAKE_CASE__ : str = re.compile(r'''^\s*try:''') # Catches a line with else: SCREAMING_SNAKE_CASE__ : Any = re.compile(r'''^\s*else:''') def a ( UpperCamelCase_ : Dict ) -> List[str]: if _re_test_backend.search(UpperCamelCase_ ) is None: return None snake_case__ =[b[0] for b in _re_backend.findall(UpperCamelCase_ )] backends.sort() return "_and_".join(UpperCamelCase_ ) def a ( UpperCamelCase_ : List[Any] ) -> Tuple: with open(UpperCamelCase_ , 'r' , encoding='utf-8' , newline='\n' ) as f: snake_case__ =f.readlines() snake_case__ =0 while line_index < len(UpperCamelCase_ ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(UpperCamelCase_ ): return None # First grab the objects without a specific backend in _import_structure snake_case__ =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: snake_case__ =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(UpperCamelCase_ ): snake_case__ =_re_one_line_import_struct.search(UpperCamelCase_ ).groups()[0] snake_case__ =re.findall(r'\[([^\]]+)\]' , UpperCamelCase_ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue snake_case__ =_re_import_struct_key_value.search(UpperCamelCase_ ) if single_line_import_search is not None: snake_case__ =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(UpperCamelCase_ ) > 0] objects.extend(UpperCamelCase_ ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 snake_case__ ={'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING' ): # If the line is an if not is_backend_available, we grab all objects associated. snake_case__ =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: snake_case__ =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 snake_case__ =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): snake_case__ =lines[line_index] if _re_import_struct_add_one.search(UpperCamelCase_ ) is not None: objects.append(_re_import_struct_add_one.search(UpperCamelCase_ ).groups()[0] ) elif _re_import_struct_add_many.search(UpperCamelCase_ ) is not None: snake_case__ =_re_import_struct_add_many.search(UpperCamelCase_ ).groups()[0].split(', ' ) snake_case__ =[obj[1:-1] for obj in imports if len(UpperCamelCase_ ) > 0] objects.extend(UpperCamelCase_ ) elif _re_between_brackets.search(UpperCamelCase_ ) is not None: snake_case__ =_re_between_brackets.search(UpperCamelCase_ ).groups()[0].split(', ' ) snake_case__ =[obj[1:-1] for obj in imports if len(UpperCamelCase_ ) > 0] objects.extend(UpperCamelCase_ ) elif _re_quote_object.search(UpperCamelCase_ ) is not None: objects.append(_re_quote_object.search(UpperCamelCase_ ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 snake_case__ =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend snake_case__ =[] while ( line_index < len(UpperCamelCase_ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): snake_case__ =lines[line_index] snake_case__ =_re_import.search(UpperCamelCase_ ) 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 snake_case__ ={'none': objects} # Let's continue with backend-specific objects while line_index < len(UpperCamelCase_ ): # If the line is an if is_backend_available, we grab all objects associated. snake_case__ =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: snake_case__ =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 snake_case__ =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): snake_case__ =lines[line_index] snake_case__ =_re_import.search(UpperCamelCase_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 12 ): objects.append(line[12:-2] ) line_index += 1 snake_case__ =objects else: line_index += 1 return import_dict_objects, type_hint_objects def a ( UpperCamelCase_ : int , UpperCamelCase_ : List[Any] ) -> Union[str, Any]: def find_duplicates(UpperCamelCase_ : Tuple ): return [k for k, v in collections.Counter(UpperCamelCase_ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] snake_case__ =[] for key in import_dict_objects.keys(): snake_case__ =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f"""Duplicate _import_structure definitions for: {duplicate_imports}""" ) snake_case__ =find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f"""Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}""" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): snake_case__ ='base imports' if key == 'none' else f"""{key} backend""" errors.append(f"""Differences for {name}:""" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f""" {a} in TYPE_HINT but not in _import_structure.""" ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f""" {a} in _import_structure but not in TYPE_HINT.""" ) return errors def a ( ) -> Optional[Any]: snake_case__ =[] for root, _, files in os.walk(UpperCamelCase_ ): if "__init__.py" in files: snake_case__ =os.path.join(UpperCamelCase_ , '__init__.py' ) snake_case__ =parse_init(UpperCamelCase_ ) if objects is not None: snake_case__ =analyze_results(*UpperCamelCase_ ) if len(UpperCamelCase_ ) > 0: snake_case__ =f"""Problem in {fname}, both halves do not define the same objects.\n{errors[0]}""" failures.append('\n'.join(UpperCamelCase_ ) ) if len(UpperCamelCase_ ) > 0: raise ValueError('\n\n'.join(UpperCamelCase_ ) ) def a ( ) -> Dict: snake_case__ =[] for path, directories, files in os.walk(UpperCamelCase_ ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(UpperCamelCase_ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(UpperCamelCase_ ) / folder).glob('*.py' ) ) ) == 0: continue snake_case__ =str((Path(UpperCamelCase_ ) / folder).relative_to(UpperCamelCase_ ) ) snake_case__ =short_path.replace(os.path.sep , '.' ) submodules.append(UpperCamelCase_ ) for fname in files: if fname == "__init__.py": continue snake_case__ =str((Path(UpperCamelCase_ ) / fname).relative_to(UpperCamelCase_ ) ) snake_case__ =short_path.replace('.py' , '' ).replace(os.path.sep , '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(UpperCamelCase_ ) return submodules SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', '''models.esm.openfold_utils''', ] def a ( ) -> Union[str, Any]: # This is to make sure the transformers module imported is the one in the repo. from transformers.utils import direct_transformers_import snake_case__ =direct_transformers_import(UpperCamelCase_ ) snake_case__ =set(transformers._import_structure.keys() ) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(UpperCamelCase_ , '__init__.py' ) , 'r' ) as f: snake_case__ =f.read() import_structure_keys.update(set(re.findall(r'import_structure\[\"([^\"]*)\"\]' , UpperCamelCase_ ) ) ) snake_case__ =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(UpperCamelCase_ ) > 0: snake_case__ ='\n'.join(f"""- {module}""" for module in module_not_registered ) raise ValueError( 'The following submodules are not properly registed in the main init of Transformers:\n' f"""{list_of_modules}\n""" 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.' ) if __name__ == "__main__": check_all_inits() check_submodules()
538
1
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar A = TypeVar('''T''') class __lowercase ( Generic[T] ): '''simple docstring''' __lowerCAmelCase = 42 # Cache store of keys __lowerCAmelCase = 42 # References of the keys in cache __lowerCAmelCase = 10 # Maximum capacity of cache def __init__( self , _UpperCAmelCase ): __a : List[Any] = deque() __a : Optional[Any] = set() if not n: __a : List[str] = sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: __a : Dict = n def _lowerCamelCase ( self , _UpperCAmelCase ): if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: __a : List[str] = self.dq_store.pop() self.key_reference.remove(_UpperCAmelCase ) else: self.dq_store.remove(_UpperCAmelCase ) self.dq_store.appendleft(_UpperCAmelCase ) self.key_reference.add(_UpperCAmelCase ) def _lowerCamelCase ( self ): for k in self.dq_store: print(_UpperCAmelCase ) def __repr__( self ): return f"""LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}""" if __name__ == "__main__": import doctest doctest.testmod() A = LRUCache(4) lru_cache.refer('''A''') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('''A''') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
101
"""simple docstring""" import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging A = logging.get_logger(__name__) # pylint: disable=invalid-name class __lowercase ( _UpperCamelCase ): '''simple docstring''' def __init__( self , _UpperCAmelCase , _UpperCAmelCase=768 ): super().__init__(_UpperCAmelCase ) __a : str = proj_size __a : Optional[Any] = CLIPVisionModel(_UpperCAmelCase ) __a : List[Any] = PaintByExampleMapper(_UpperCAmelCase ) __a : int = nn.LayerNorm(config.hidden_size ) __a : List[Any] = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling __a : int = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def _lowerCamelCase ( self , _UpperCAmelCase , _UpperCAmelCase=False ): __a : str = self.model(pixel_values=_UpperCAmelCase ) __a : Union[str, Any] = clip_output.pooler_output __a : Optional[int] = self.mapper(latent_states[:, None] ) __a : int = self.final_layer_norm(_UpperCAmelCase ) __a : Optional[Any] = self.proj_out(_UpperCAmelCase ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class __lowercase ( nn.Module ): '''simple docstring''' def __init__( self , _UpperCAmelCase ): super().__init__() __a : List[str] = (config.num_hidden_layers + 1) // 5 __a : Optional[Any] = config.hidden_size __a : str = 1 __a : Union[str, Any] = nn.ModuleList( [ BasicTransformerBlock(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , activation_fn='''gelu''' , attention_bias=_UpperCAmelCase ) for _ in range(_UpperCAmelCase ) ] ) def _lowerCamelCase ( self , _UpperCAmelCase ): for block in self.blocks: __a : Union[str, Any] = block(_UpperCAmelCase ) return hidden_states
101
1
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case__ = logging.get_logger(__name__) snake_case__ = { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/config.json''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/config.json''', } class lowerCAmelCase_ ( _a): lowerCamelCase_ = 'xlnet' lowerCamelCase_ = ['mems'] lowerCamelCase_ = { 'n_token': 'vocab_size', # Backward compatibility 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : int , __A : Optional[Any]=32000 , __A : List[str]=1024 , __A : Optional[int]=24 , __A : int=16 , __A : Tuple=4096 , __A : List[Any]="gelu" , __A : str=True , __A : Dict="bi" , __A : List[str]=0.02 , __A : Union[str, Any]=1E-12 , __A : int=0.1 , __A : List[str]=512 , __A : Optional[Any]=None , __A : Union[str, Any]=True , __A : str=False , __A : List[str]=False , __A : str=-1 , __A : Dict=False , __A : Union[str, Any]="last" , __A : Any=True , __A : int="tanh" , __A : Union[str, Any]=0.1 , __A : Any=5 , __A : Union[str, Any]=5 , __A : Dict=5 , __A : List[str]=1 , __A : Any=2 , **__A : int , ) ->Union[str, Any]: """simple docstring""" a__ :List[Any] = vocab_size a__ :int = d_model a__ :Tuple = n_layer a__ :List[Any] = n_head if d_model % n_head != 0: raise ValueError(F'''\'d_model % n_head\' ({d_model % n_head}) should be equal to 0''' ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( F'''`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})''' ) a__ :Union[str, Any] = d_model // n_head a__ :Optional[Any] = ff_activation a__ :Optional[int] = d_inner a__ :Optional[int] = untie_r a__ :Optional[Any] = attn_type a__ :Tuple = initializer_range a__ :Tuple = layer_norm_eps a__ :int = dropout a__ :Optional[int] = mem_len a__ :List[Any] = reuse_len a__ :Optional[int] = bi_data a__ :Tuple = clamp_len a__ :int = same_length a__ :List[Any] = summary_type a__ :Any = summary_use_proj a__ :Dict = summary_activation a__ :int = summary_last_dropout a__ :Union[str, Any] = start_n_top a__ :List[Any] = end_n_top a__ :Union[str, Any] = bos_token_id a__ :List[str] = pad_token_id a__ :List[Any] = eos_token_id if "use_cache" in kwargs: warnings.warn( "The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`" " instead." , __A , ) a__ :Optional[Any] = kwargs["use_cache"] a__ :List[Any] = use_mems_eval a__ :Optional[Any] = use_mems_train super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A ) @property def _snake_case ( self : str ) ->Union[str, Any]: """simple docstring""" logger.info(F'''The model {self.model_type} is one of the few models that has no sequence length limit.''' ) return -1 @max_position_embeddings.setter def _snake_case ( self : List[str] , __A : Any ) ->Optional[Any]: """simple docstring""" raise NotImplementedError( F'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
395
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowerCAmelCase_ : def __init__( self : Dict , __A : Optional[int] , __A : int=2 , __A : str=True , __A : List[Any]=False , __A : List[str]=10 , __A : Union[str, Any]=3 , __A : Dict=32 * 8 , __A : str=32 * 8 , __A : int=4 , __A : List[str]=64 , ) ->Tuple: """simple docstring""" a__ :Optional[Any] = parent a__ :Dict = batch_size a__ :str = is_training a__ :Optional[int] = use_auxiliary_loss a__ :str = num_queries a__ :int = num_channels a__ :Optional[int] = min_size a__ :Optional[Any] = max_size a__ :Dict = num_labels a__ :Union[str, Any] = hidden_dim a__ :Any = hidden_dim def _snake_case ( self : Tuple ) ->List[str]: """simple docstring""" a__ :Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __A ) a__ :Optional[int] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__A ) a__ :Optional[int] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__A ) > 0.5 ).float() a__ :List[str] = (torch.rand((self.batch_size, self.num_labels) , device=__A ) > 0.5).long() a__ :Tuple = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _snake_case ( self : Tuple ) ->Union[str, Any]: """simple docstring""" a__ :List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) a__ :List[str] = self.num_queries a__ :Optional[int] = self.num_labels a__ :Tuple = [1, 1, 1, 1] a__ :Dict = self.num_channels a__ :Optional[Any] = 64 a__ :Union[str, Any] = 128 a__ :Optional[Any] = self.hidden_dim a__ :int = self.hidden_dim a__ :List[str] = self.hidden_dim return config def _snake_case ( self : Any ) ->Dict: """simple docstring""" a__ , a__ , a__ , a__ , a__ :int = self.prepare_config_and_inputs() a__ :Optional[int] = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def _snake_case ( self : int , __A : Union[str, Any] , __A : Tuple ) ->List[Any]: """simple docstring""" a__ :Tuple = output.encoder_hidden_states a__ :List[Any] = output.pixel_decoder_hidden_states a__ :Optional[Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__A ) , config.decoder_layers ) def _snake_case ( self : Dict , __A : List[str] , __A : Tuple , __A : Union[str, Any] , __A : Dict=False ) ->Any: """simple docstring""" with torch.no_grad(): a__ :Dict = MaskaFormerModel(config=__A ) model.to(__A ) model.eval() a__ :Tuple = model(pixel_values=__A , pixel_mask=__A ) a__ :Dict = model(__A , output_hidden_states=__A ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(__A , __A ) def _snake_case ( self : Optional[int] , __A : int , __A : str , __A : Tuple , __A : List[Any] , __A : List[str] ) ->Any: """simple docstring""" a__ :Dict = MaskaFormerForUniversalSegmentation(config=__A ) model.to(__A ) model.eval() def comm_check_on_output(__A : Tuple ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): a__ :Union[str, Any] = model(pixel_values=__A , pixel_mask=__A ) a__ :List[Any] = model(__A ) comm_check_on_output(__A ) a__ :str = model( pixel_values=__A , pixel_mask=__A , mask_labels=__A , class_labels=__A ) comm_check_on_output(__A ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class lowerCAmelCase_ ( _a ,_a ,unittest.TestCase): lowerCamelCase_ = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () lowerCamelCase_ = {'feature-extraction': MaskaFormerModel} if is_torch_available() else {} lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self : Tuple ) ->Dict: """simple docstring""" a__ :List[str] = MaskaFormerModelTester(self ) a__ :List[str] = ConfigTester(self , config_class=__A , has_text_modality=__A ) def _snake_case ( self : Tuple ) ->str: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self : str ) ->Tuple: """simple docstring""" a__ , a__ :str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__A , **__A , output_hidden_states=__A ) def _snake_case ( self : Union[str, Any] ) ->int: """simple docstring""" a__ :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__A ) @unittest.skip(reason="Mask2Former does not use inputs_embeds" ) def _snake_case ( self : List[str] ) ->Optional[Any]: """simple docstring""" pass @unittest.skip(reason="Mask2Former does not have a get_input_embeddings method" ) def _snake_case ( self : int ) ->Dict: """simple docstring""" pass @unittest.skip(reason="Mask2Former is not a generative model" ) def _snake_case ( self : Any ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="Mask2Former does not use token embeddings" ) def _snake_case ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" pass @require_torch_multi_gpu @unittest.skip( reason="Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def _snake_case ( self : str ) ->str: """simple docstring""" pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _snake_case ( self : Optional[int] ) ->Any: """simple docstring""" pass def _snake_case ( self : Any ) ->Union[str, Any]: """simple docstring""" a__ , a__ :Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ :Any = model_class(__A ) a__ :Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ :Optional[Any] = [*signature.parameters.keys()] a__ :str = ["pixel_values"] self.assertListEqual(arg_names[:1] , __A ) @slow def _snake_case ( self : Dict ) ->str: """simple docstring""" for model_name in ["facebook/mask2former-swin-small-coco-instance"]: a__ :Any = MaskaFormerModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def _snake_case ( self : List[str] ) ->List[Any]: """simple docstring""" a__ :Tuple = (self.model_tester.min_size,) * 2 a__ :Optional[int] = { "pixel_values": torch.randn((2, 3, *size) , device=__A ), "mask_labels": torch.randn((2, 10, *size) , device=__A ), "class_labels": torch.zeros(2 , 10 , device=__A ).long(), } a__ :Dict = self.model_tester.get_config() a__ :str = MaskaFormerForUniversalSegmentation(__A ).to(__A ) a__ :int = model(**__A ) self.assertTrue(outputs.loss is not None ) def _snake_case ( self : List[str] ) ->Any: """simple docstring""" a__ , a__ :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__A , **__A , output_hidden_states=__A ) def _snake_case ( self : Tuple ) ->Tuple: """simple docstring""" a__ , a__ :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ :Union[str, Any] = model_class(__A ).to(__A ) a__ :int = model(**__A , output_attentions=__A ) self.assertTrue(outputs.attentions is not None ) def _snake_case ( self : Any ) ->Any: """simple docstring""" if not self.model_tester.is_training: return a__ :str = self.all_model_classes[1] a__ , a__ , a__ , a__ , a__ :Any = self.model_tester.prepare_config_and_inputs() a__ :Optional[Any] = model_class(__A ) model.to(__A ) model.train() a__ :Any = model(__A , mask_labels=__A , class_labels=__A ).loss loss.backward() def _snake_case ( self : Tuple ) ->Optional[Any]: """simple docstring""" a__ :List[str] = self.all_model_classes[1] a__ , a__ , a__ , a__ , a__ :int = self.model_tester.prepare_config_and_inputs() a__ :Optional[Any] = True a__ :Optional[int] = True a__ :List[Any] = model_class(__A ).to(__A ) model.train() a__ :Optional[Any] = model(__A , mask_labels=__A , class_labels=__A ) a__ :int = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() a__ :List[str] = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() a__ :List[Any] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() a__ :Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=__A ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) snake_case__ = 1e-4 def lowerCamelCase__ ( ) -> Optional[int]: """simple docstring""" a__ :Dict = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class lowerCAmelCase_ ( unittest.TestCase): @cached_property def _snake_case ( self : int ) ->Optional[int]: """simple docstring""" return "facebook/mask2former-swin-small-coco-instance" @cached_property def _snake_case ( self : int ) ->Dict: """simple docstring""" return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def _snake_case ( self : str ) ->int: """simple docstring""" a__ :Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(__A ) a__ :List[Any] = self.default_image_processor a__ :str = prepare_img() a__ :Union[str, Any] = image_processor(__A , return_tensors="pt" ).to(__A ) a__ :Union[str, Any] = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__A , (1, 3, 384, 384) ) with torch.no_grad(): a__ :Optional[int] = model(**__A ) a__ :str = torch.tensor( [[-0.2_790, -1.0_717, -1.1_668], [-0.5_128, -0.3_128, -0.4_987], [-0.5_832, 0.1_971, -0.0_197]] ).to(__A ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) ) a__ :Dict = torch.tensor( [[0.8_973, 1.1_847, 1.1_776], [1.1_934, 1.5_040, 1.5_128], [1.1_153, 1.4_486, 1.4_951]] ).to(__A ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) ) a__ :Union[str, Any] = torch.tensor( [[2.1_152, 1.7_000, -0.8_603], [1.5_808, 1.8_004, -0.9_353], [1.6_043, 1.7_495, -0.5_999]] ).to(__A ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __A , atol=__A ) ) def _snake_case ( self : Any ) ->Dict: """simple docstring""" a__ :Dict = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__A ).eval() a__ :Tuple = self.default_image_processor a__ :Any = prepare_img() a__ :str = image_processor(__A , return_tensors="pt" ).to(__A ) a__ :Any = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__A , (1, 3, 384, 384) ) with torch.no_grad(): a__ :int = model(**__A ) # masks_queries_logits a__ :Optional[Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) a__ :Dict = [ [-8.7_839, -9.0_056, -8.8_121], [-7.4_104, -7.0_313, -6.5_401], [-6.6_105, -6.3_427, -6.4_675], ] a__ :Any = torch.tensor(__A ).to(__A ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) ) # class_queries_logits a__ :Tuple = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) a__ :Optional[int] = torch.tensor( [ [1.8_324, -8.0_835, -4.1_922], [0.8_450, -9.0_050, -3.6_053], [0.3_045, -7.7_293, -3.0_275], ] ).to(__A ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) ) def _snake_case ( self : List[str] ) ->List[Any]: """simple docstring""" a__ :List[str] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__A ).eval() a__ :Tuple = self.default_image_processor a__ :str = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) a__ :Tuple = inputs["pixel_values"].to(__A ) a__ :List[Any] = [el.to(__A ) for el in inputs["mask_labels"]] a__ :List[str] = [el.to(__A ) for el in inputs["class_labels"]] with torch.no_grad(): a__ :List[str] = model(**__A ) self.assertTrue(outputs.loss is not None )
395
1
from __future__ import annotations def __SCREAMING_SNAKE_CASE ( UpperCamelCase : list[int] ) -> int: """simple docstring""" a_ = len(UpperCamelCase ) // 2 # choose the middle 3 elements a_ = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
702
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def __SCREAMING_SNAKE_CASE ( UpperCamelCase : Tuple ) -> Tuple: """simple docstring""" if isinstance(UpperCamelCase , collections.abc.Iterable ): return x return (x, x) @require_flax class lowerCamelCase_ : def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): pass def __magic_name__ ( self ): pass def __magic_name__ ( self ): pass def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a_ = np.abs((a - b) ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , f"""Difference between torch and flax is {diff} (>= {tol}).""" ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): a_ = VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) a_ = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], config.projection_dim) ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): a_ , a_ = self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = {"""vision_model""": vision_model, """text_model""": text_model} a_ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE ) a_ = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): a_ , a_ = self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = {"""vision_model""": vision_model, """text_model""": text_model} a_ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE ) a_ = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) a_ = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE ) a_ = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) a_ = after_output[0] a_ = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-3 ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): a_ , a_ = self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = {"""vision_model""": vision_model, """text_model""": text_model} a_ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE ) a_ = model( input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) a_ = output.vision_model_output.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) a_ = to_atuple(vision_model.config.image_size ) a_ = to_atuple(vision_model.config.patch_size ) a_ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) a_ = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) a_ = output.text_model_output.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): pt_model.to(_SCREAMING_SNAKE_CASE ) pt_model.eval() # prepare inputs a_ = inputs_dict a_ = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): a_ = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() a_ = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(_SCREAMING_SNAKE_CASE , pt_output.numpy() , 4E-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) a_ = fx_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(_SCREAMING_SNAKE_CASE , pt_output.numpy() , 4E-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_SCREAMING_SNAKE_CASE ) a_ = VisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_flax=_SCREAMING_SNAKE_CASE ) pt_model_loaded.to(_SCREAMING_SNAKE_CASE ) pt_model_loaded.eval() with torch.no_grad(): a_ = pt_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(_SCREAMING_SNAKE_CASE , pt_output_loaded.numpy() , 4E-2 ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a_ = VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) a_ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _SCREAMING_SNAKE_CASE ) a_ = fx_state self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a_ = VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) a_ = load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , fx_model.params ) self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_SCREAMING_SNAKE_CASE ) def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_SCREAMING_SNAKE_CASE ) def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() self.check_save_load(**_SCREAMING_SNAKE_CASE ) def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_SCREAMING_SNAKE_CASE ) @is_pt_flax_cross_test def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() a_ = config_inputs_dict.pop("""vision_config""" ) a_ = config_inputs_dict.pop("""text_config""" ) a_ = config_inputs_dict self.check_equivalence_pt_to_flax(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.check_equivalence_flax_to_pt(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __magic_name__ ( self ): a_ , a_ = self.get_pretrained_model_and_inputs() a_ = model_a(**_SCREAMING_SNAKE_CASE ) a_ = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE ) a_ = model_a(**_SCREAMING_SNAKE_CASE ) a_ = after_outputs[0] a_ = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-5 ) @require_flax class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): def __magic_name__ ( self ): a_ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( """hf-internal-testing/tiny-random-vit""" , """hf-internal-testing/tiny-bert""" , vision_from_pt=_SCREAMING_SNAKE_CASE , text_from_pt=_SCREAMING_SNAKE_CASE , ) a_ = 13 a_ = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) a_ = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) a_ = random_attention_mask([batch_size, 4] ) a_ = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a_ = FlaxViTModel(_SCREAMING_SNAKE_CASE ) a_ = FlaxBertModel(_SCREAMING_SNAKE_CASE ) return vision_model, text_model def __magic_name__ ( self ): a_ = FlaxViTModelTester(self ) a_ = FlaxBertModelTester(self ) a_ = vit_model_tester.prepare_config_and_inputs() a_ = bert_model_tester.prepare_config_and_inputs() a_ , a_ = vision_config_and_inputs a_ , a_ , a_ , a_ = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): def __magic_name__ ( self ): a_ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( """hf-internal-testing/tiny-random-clip""" , """hf-internal-testing/tiny-bert""" , vision_from_pt=_SCREAMING_SNAKE_CASE , text_from_pt=_SCREAMING_SNAKE_CASE , ) a_ = 13 a_ = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) a_ = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) a_ = random_attention_mask([batch_size, 4] ) a_ = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a_ = FlaxCLIPVisionModel(_SCREAMING_SNAKE_CASE ) a_ = FlaxBertModel(_SCREAMING_SNAKE_CASE ) return vision_model, text_model def __magic_name__ ( self ): a_ = FlaxCLIPVisionModelTester(self ) a_ = FlaxBertModelTester(self ) a_ = clip_model_tester.prepare_config_and_inputs() a_ = bert_model_tester.prepare_config_and_inputs() a_ , a_ = vision_config_and_inputs a_ , a_ , a_ , a_ = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class lowerCamelCase_ ( unittest.TestCase ): @slow def __magic_name__ ( self ): a_ = FlaxVisionTextDualEncoderModel.from_pretrained("""clip-italian/clip-italian""" , logit_scale_init_value=1.0 ) a_ = VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian""" ) a_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) a_ = processor( text=["""una foto di un gatto""", """una foto di un cane"""] , images=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="""np""" ) a_ = model(**_SCREAMING_SNAKE_CASE ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) a_ = np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]] ) self.assertTrue(np.allclose(outputs.logits_per_image , _SCREAMING_SNAKE_CASE , atol=1E-3 ) )
403
0
'''simple docstring''' from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case ( lowercase ): """simple docstring""" def __init__( self , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = None , ): """simple docstring""" super().__init__() self.register_modules(transformer=UpperCamelCase , vae=UpperCamelCase , scheduler=UpperCamelCase ) # create a imagenet -> id dictionary for easier use lowerCamelCase_ = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split("," ): lowerCamelCase_ = int(UpperCamelCase ) lowerCamelCase_ = dict(sorted(self.labels.items() ) ) def snake_case ( self , UpperCamelCase ): """simple docstring""" if not isinstance(UpperCamelCase , UpperCamelCase ): lowerCamelCase_ = list(UpperCamelCase ) for l in label: if l not in self.labels: raise ValueError( f'''{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.''' ) return [self.labels[l] for l in label] @torch.no_grad() def __call__( self , UpperCamelCase , UpperCamelCase = 4.0 , UpperCamelCase = None , UpperCamelCase = 50 , UpperCamelCase = "pil" , UpperCamelCase = True , ): """simple docstring""" lowerCamelCase_ = len(UpperCamelCase ) lowerCamelCase_ = self.transformer.config.sample_size lowerCamelCase_ = self.transformer.config.in_channels lowerCamelCase_ = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=UpperCamelCase , device=self.device , dtype=self.transformer.dtype , ) lowerCamelCase_ = torch.cat([latents] * 2 ) if guidance_scale > 1 else latents lowerCamelCase_ = torch.tensor(UpperCamelCase , device=self.device ).reshape(-1 ) lowerCamelCase_ = torch.tensor([1000] * batch_size , device=self.device ) lowerCamelCase_ = torch.cat([class_labels, class_null] , 0 ) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(UpperCamelCase ) for t in self.progress_bar(self.scheduler.timesteps ): if guidance_scale > 1: lowerCamelCase_ = latent_model_input[: len(UpperCamelCase ) // 2] lowerCamelCase_ = torch.cat([half, half] , dim=0 ) lowerCamelCase_ = self.scheduler.scale_model_input(UpperCamelCase , UpperCamelCase ) lowerCamelCase_ = t if not torch.is_tensor(UpperCamelCase ): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) lowerCamelCase_ = latent_model_input.device.type == "mps" if isinstance(UpperCamelCase , UpperCamelCase ): lowerCamelCase_ = torch.floataa if is_mps else torch.floataa else: lowerCamelCase_ = torch.intaa if is_mps else torch.intaa lowerCamelCase_ = torch.tensor([timesteps] , dtype=UpperCamelCase , device=latent_model_input.device ) elif len(timesteps.shape ) == 0: lowerCamelCase_ = timesteps[None].to(latent_model_input.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML lowerCamelCase_ = timesteps.expand(latent_model_input.shape[0] ) # predict noise model_output lowerCamelCase_ = self.transformer( UpperCamelCase , timestep=UpperCamelCase , class_labels=UpperCamelCase ).sample # perform guidance if guidance_scale > 1: lowerCamelCase_ ,lowerCamelCase_ = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] lowerCamelCase_ ,lowerCamelCase_ = torch.split(UpperCamelCase , len(UpperCamelCase ) // 2 , dim=0 ) lowerCamelCase_ = uncond_eps + guidance_scale * (cond_eps - uncond_eps) lowerCamelCase_ = torch.cat([half_eps, half_eps] , dim=0 ) lowerCamelCase_ = torch.cat([eps, rest] , dim=1 ) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: lowerCamelCase_ ,lowerCamelCase_ = torch.split(UpperCamelCase , UpperCamelCase , dim=1 ) else: lowerCamelCase_ = noise_pred # compute previous image: x_t -> x_t-1 lowerCamelCase_ = self.scheduler.step(UpperCamelCase , UpperCamelCase , UpperCamelCase ).prev_sample if guidance_scale > 1: lowerCamelCase_ ,lowerCamelCase_ = latent_model_input.chunk(2 , dim=0 ) else: lowerCamelCase_ = latent_model_input lowerCamelCase_ = 1 / self.vae.config.scaling_factor * latents lowerCamelCase_ = self.vae.decode(UpperCamelCase ).sample lowerCamelCase_ = (samples / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCamelCase_ = samples.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": lowerCamelCase_ = self.numpy_to_pil(UpperCamelCase ) if not return_dict: return (samples,) return ImagePipelineOutput(images=UpperCamelCase )
675
'''simple docstring''' import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() a_ : Optional[Any] = logging.get_logger("""transformers.models.encodec""") a_ : List[str] = { """quantizer.vq.layers.*._codebook.inited""": """quantizer.layers.*.codebook.inited""", """quantizer.vq.layers.*._codebook.cluster_size""": """quantizer.layers.*.codebook.cluster_size""", """quantizer.vq.layers.*._codebook.embed""": """quantizer.layers.*.codebook.embed""", """quantizer.vq.layers.*._codebook.embed_avg""": """quantizer.layers.*.codebook.embed_avg""", } a_ : Optional[int] = { """encoder.model.0.conv.conv""": """encoder.layers.0.conv""", """encoder.model.1.block.1.conv.conv""": """encoder.layers.1.block.1.conv""", """encoder.model.1.block.3.conv.conv""": """encoder.layers.1.block.3.conv""", """encoder.model.1.shortcut.conv.conv""": """encoder.layers.1.shortcut.conv""", """encoder.model.3.conv.conv""": """encoder.layers.3.conv""", """encoder.model.4.block.1.conv.conv""": """encoder.layers.4.block.1.conv""", """encoder.model.4.block.3.conv.conv""": """encoder.layers.4.block.3.conv""", """encoder.model.4.shortcut.conv.conv""": """encoder.layers.4.shortcut.conv""", """encoder.model.6.conv.conv""": """encoder.layers.6.conv""", """encoder.model.7.block.1.conv.conv""": """encoder.layers.7.block.1.conv""", """encoder.model.7.block.3.conv.conv""": """encoder.layers.7.block.3.conv""", """encoder.model.7.shortcut.conv.conv""": """encoder.layers.7.shortcut.conv""", """encoder.model.9.conv.conv""": """encoder.layers.9.conv""", """encoder.model.10.block.1.conv.conv""": """encoder.layers.10.block.1.conv""", """encoder.model.10.block.3.conv.conv""": """encoder.layers.10.block.3.conv""", """encoder.model.10.shortcut.conv.conv""": """encoder.layers.10.shortcut.conv""", """encoder.model.12.conv.conv""": """encoder.layers.12.conv""", """encoder.model.13.lstm""": """encoder.layers.13.lstm""", """encoder.model.15.conv.conv""": """encoder.layers.15.conv""", } a_ : Tuple = { """encoder.model.0.conv.norm""": """encoder.layers.0.norm""", """encoder.model.1.block.1.conv.norm""": """encoder.layers.1.block.1.norm""", """encoder.model.1.block.3.conv.norm""": """encoder.layers.1.block.3.norm""", """encoder.model.1.shortcut.conv.norm""": """encoder.layers.1.shortcut.norm""", """encoder.model.3.conv.norm""": """encoder.layers.3.norm""", """encoder.model.4.block.1.conv.norm""": """encoder.layers.4.block.1.norm""", """encoder.model.4.block.3.conv.norm""": """encoder.layers.4.block.3.norm""", """encoder.model.4.shortcut.conv.norm""": """encoder.layers.4.shortcut.norm""", """encoder.model.6.conv.norm""": """encoder.layers.6.norm""", """encoder.model.7.block.1.conv.norm""": """encoder.layers.7.block.1.norm""", """encoder.model.7.block.3.conv.norm""": """encoder.layers.7.block.3.norm""", """encoder.model.7.shortcut.conv.norm""": """encoder.layers.7.shortcut.norm""", """encoder.model.9.conv.norm""": """encoder.layers.9.norm""", """encoder.model.10.block.1.conv.norm""": """encoder.layers.10.block.1.norm""", """encoder.model.10.block.3.conv.norm""": """encoder.layers.10.block.3.norm""", """encoder.model.10.shortcut.conv.norm""": """encoder.layers.10.shortcut.norm""", """encoder.model.12.conv.norm""": """encoder.layers.12.norm""", """encoder.model.15.conv.norm""": """encoder.layers.15.norm""", } a_ : Union[str, Any] = { """decoder.model.0.conv.conv""": """decoder.layers.0.conv""", """decoder.model.1.lstm""": """decoder.layers.1.lstm""", """decoder.model.3.convtr.convtr""": """decoder.layers.3.conv""", """decoder.model.4.block.1.conv.conv""": """decoder.layers.4.block.1.conv""", """decoder.model.4.block.3.conv.conv""": """decoder.layers.4.block.3.conv""", """decoder.model.4.shortcut.conv.conv""": """decoder.layers.4.shortcut.conv""", """decoder.model.6.convtr.convtr""": """decoder.layers.6.conv""", """decoder.model.7.block.1.conv.conv""": """decoder.layers.7.block.1.conv""", """decoder.model.7.block.3.conv.conv""": """decoder.layers.7.block.3.conv""", """decoder.model.7.shortcut.conv.conv""": """decoder.layers.7.shortcut.conv""", """decoder.model.9.convtr.convtr""": """decoder.layers.9.conv""", """decoder.model.10.block.1.conv.conv""": """decoder.layers.10.block.1.conv""", """decoder.model.10.block.3.conv.conv""": """decoder.layers.10.block.3.conv""", """decoder.model.10.shortcut.conv.conv""": """decoder.layers.10.shortcut.conv""", """decoder.model.12.convtr.convtr""": """decoder.layers.12.conv""", """decoder.model.13.block.1.conv.conv""": """decoder.layers.13.block.1.conv""", """decoder.model.13.block.3.conv.conv""": """decoder.layers.13.block.3.conv""", """decoder.model.13.shortcut.conv.conv""": """decoder.layers.13.shortcut.conv""", """decoder.model.15.conv.conv""": """decoder.layers.15.conv""", } a_ : Union[str, Any] = { """decoder.model.0.conv.norm""": """decoder.layers.0.norm""", """decoder.model.3.convtr.norm""": """decoder.layers.3.norm""", """decoder.model.4.block.1.conv.norm""": """decoder.layers.4.block.1.norm""", """decoder.model.4.block.3.conv.norm""": """decoder.layers.4.block.3.norm""", """decoder.model.4.shortcut.conv.norm""": """decoder.layers.4.shortcut.norm""", """decoder.model.6.convtr.norm""": """decoder.layers.6.norm""", """decoder.model.7.block.1.conv.norm""": """decoder.layers.7.block.1.norm""", """decoder.model.7.block.3.conv.norm""": """decoder.layers.7.block.3.norm""", """decoder.model.7.shortcut.conv.norm""": """decoder.layers.7.shortcut.norm""", """decoder.model.9.convtr.norm""": """decoder.layers.9.norm""", """decoder.model.10.block.1.conv.norm""": """decoder.layers.10.block.1.norm""", """decoder.model.10.block.3.conv.norm""": """decoder.layers.10.block.3.norm""", """decoder.model.10.shortcut.conv.norm""": """decoder.layers.10.shortcut.norm""", """decoder.model.12.convtr.norm""": """decoder.layers.12.norm""", """decoder.model.13.block.1.conv.norm""": """decoder.layers.13.block.1.norm""", """decoder.model.13.block.3.conv.norm""": """decoder.layers.13.block.3.norm""", """decoder.model.13.shortcut.conv.norm""": """decoder.layers.13.shortcut.norm""", """decoder.model.15.conv.norm""": """decoder.layers.15.norm""", } a_ : Optional[Any] = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } a_ : List[str] = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } a_ : Any = [] a_ : str = [] def __snake_case ( UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple ): for attribute in key.split("." ): lowerCamelCase_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) if weight_type is not None: lowerCamelCase_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ).shape else: lowerCamelCase_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": lowerCamelCase_ = value elif weight_type == "weight_g": lowerCamelCase_ = value elif weight_type == "weight_v": lowerCamelCase_ = value elif weight_type == "bias": lowerCamelCase_ = value elif weight_type == "running_mean": lowerCamelCase_ = value elif weight_type == "running_var": lowerCamelCase_ = value elif weight_type == "num_batches_tracked": lowerCamelCase_ = value elif weight_type == "weight_ih_l0": lowerCamelCase_ = value elif weight_type == "weight_hh_l0": lowerCamelCase_ = value elif weight_type == "bias_ih_l0": lowerCamelCase_ = value elif weight_type == "bias_hh_l0": lowerCamelCase_ = value elif weight_type == "weight_ih_l1": lowerCamelCase_ = value elif weight_type == "weight_hh_l1": lowerCamelCase_ = value elif weight_type == "bias_ih_l1": lowerCamelCase_ = value elif weight_type == "bias_hh_l1": lowerCamelCase_ = value else: lowerCamelCase_ = value logger.info(F'''{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.''' ) def __snake_case ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int] ): for key in ignore_keys: if key.endswith(".*" ): if name.startswith(key[:-1] ): return True elif ".*." in key: lowerCamelCase_ ,lowerCamelCase_ = key.split(".*." ) if prefix in name and suffix in name: return True elif key in name: return True return False def __snake_case ( UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple ): lowerCamelCase_ = [] if model_name == "encodec_24khz" or "encodec_32khz": lowerCamelCase_ = MAPPING_24K elif model_name == "encodec_48khz": lowerCamelCase_ = MAPPING_48K else: raise ValueError(F'''Unsupported model: {model_name}''' ) for name, value in orig_dict.items(): if should_ignore(UpperCAmelCase_ , UpperCAmelCase_ ): logger.info(F'''{name} was ignored''' ) continue lowerCamelCase_ = False for key, mapped_key in MAPPING.items(): if "*" in key: lowerCamelCase_ ,lowerCamelCase_ = key.split(".*." ) if prefix in name and suffix in name: lowerCamelCase_ = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith("embed" ) and name.endswith("embed_avg" ): continue lowerCamelCase_ = True if "*" in mapped_key: lowerCamelCase_ = name.split(UpperCAmelCase_ )[0].split("." )[-2] lowerCamelCase_ = mapped_key.replace("*" , UpperCAmelCase_ ) if "weight_g" in name: lowerCamelCase_ = "weight_g" elif "weight_v" in name: lowerCamelCase_ = "weight_v" elif "weight_ih_l0" in name: lowerCamelCase_ = "weight_ih_l0" elif "weight_hh_l0" in name: lowerCamelCase_ = "weight_hh_l0" elif "bias_ih_l0" in name: lowerCamelCase_ = "bias_ih_l0" elif "bias_hh_l0" in name: lowerCamelCase_ = "bias_hh_l0" elif "weight_ih_l1" in name: lowerCamelCase_ = "weight_ih_l1" elif "weight_hh_l1" in name: lowerCamelCase_ = "weight_hh_l1" elif "bias_ih_l1" in name: lowerCamelCase_ = "bias_ih_l1" elif "bias_hh_l1" in name: lowerCamelCase_ = "bias_hh_l1" elif "bias" in name: lowerCamelCase_ = "bias" elif "weight" in name: lowerCamelCase_ = "weight" elif "running_mean" in name: lowerCamelCase_ = "running_mean" elif "running_var" in name: lowerCamelCase_ = "running_var" elif "num_batches_tracked" in name: lowerCamelCase_ = "num_batches_tracked" else: lowerCamelCase_ = None set_recursively(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) continue if not is_used: unused_weights.append(UpperCAmelCase_ ) logger.warning(F'''Unused weights: {unused_weights}''' ) @torch.no_grad() def __snake_case ( UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Optional[int]=None , ): if config_path is not None: lowerCamelCase_ = EncodecConfig.from_pretrained(UpperCAmelCase_ ) else: lowerCamelCase_ = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": lowerCamelCase_ = [8, 5, 4, 4] lowerCamelCase_ = [2.2] lowerCamelCase_ = 64 lowerCamelCase_ = 32000 lowerCamelCase_ = 2048 lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False elif model_name == "encodec_48khz": lowerCamelCase_ = [8, 5, 4, 2] lowerCamelCase_ = [3.0, 6.0, 12.0, 24.0] lowerCamelCase_ = 48000 lowerCamelCase_ = 2 lowerCamelCase_ = False lowerCamelCase_ = "time_group_norm" lowerCamelCase_ = True lowerCamelCase_ = 1.0 lowerCamelCase_ = 0.01 else: raise ValueError(F'''Unknown model name: {model_name}''' ) lowerCamelCase_ = EncodecModel(UpperCAmelCase_ ) lowerCamelCase_ = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(UpperCAmelCase_ ) lowerCamelCase_ = torch.load(UpperCAmelCase_ ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights lowerCamelCase_ = original_checkpoint["best_state"] recursively_load_weights(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) model.save_pretrained(UpperCAmelCase_ ) if repo_id: print("Pushing to the hub..." ) feature_extractor.push_to_hub(UpperCAmelCase_ ) model.push_to_hub(UpperCAmelCase_ ) if __name__ == "__main__": a_ : Dict = argparse.ArgumentParser() parser.add_argument( """--model""", default="""encodec_24khz""", type=str, help="""The model to convert. Should be one of 'encodec_24khz', 'encodec_32khz', 'encodec_48khz'.""", ) parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) a_ : str = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
675
1
"""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 UpperCAmelCase__ ( UpperCamelCase ): lowerCAmelCase_ : int = ["""image_processor""", """tokenizer"""] lowerCAmelCase_ : str = """ViltImageProcessor""" lowerCAmelCase_ : List[str] = ("""BertTokenizer""", """BertTokenizerFast""") def __init__( self : List[Any] , snake_case : Tuple=None , snake_case : str=None , **snake_case : Any ) -> Dict: '''simple docstring''' 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.' , snake_case , ) 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__(snake_case , snake_case ) A = self.image_processor def __call__( self : Tuple , snake_case : Union[str, Any] , snake_case : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , snake_case : bool = True , snake_case : Union[bool, str, PaddingStrategy] = False , snake_case : Union[bool, str, TruncationStrategy] = None , snake_case : Optional[int] = None , snake_case : int = 0 , snake_case : Optional[int] = None , snake_case : Optional[bool] = None , snake_case : Optional[bool] = None , snake_case : bool = False , snake_case : bool = False , snake_case : bool = False , snake_case : bool = False , snake_case : bool = True , snake_case : Optional[Union[str, TensorType]] = None , **snake_case : int , ) -> BatchEncoding: '''simple docstring''' A = self.tokenizer( text=snake_case , add_special_tokens=snake_case , padding=snake_case , truncation=snake_case , max_length=snake_case , stride=snake_case , pad_to_multiple_of=snake_case , return_token_type_ids=snake_case , return_attention_mask=snake_case , return_overflowing_tokens=snake_case , return_special_tokens_mask=snake_case , return_offsets_mapping=snake_case , return_length=snake_case , verbose=snake_case , return_tensors=snake_case , **snake_case , ) # add pixel_values + pixel_mask A = self.image_processor(snake_case , return_tensors=snake_case ) encoding.update(snake_case ) return encoding def A_ ( self : str , *snake_case : Dict , **snake_case : Optional[Any] ) -> List[str]: '''simple docstring''' return self.tokenizer.batch_decode(*snake_case , **snake_case ) def A_ ( self : Union[str, Any] , *snake_case : Optional[Any] , **snake_case : int ) -> str: '''simple docstring''' return self.tokenizer.decode(*snake_case , **snake_case ) @property def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' A = self.tokenizer.model_input_names A = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , snake_case , ) return self.image_processor_class @property def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , snake_case , ) return self.image_processor
709
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer A = ['bert-base-uncased', 'bert-base-cased'] A = 'hf-internal-testing/tiny-bert-tf-only' if is_tf_available(): class UpperCAmelCase__ ( tf.keras.Model ): def __init__( self : Tuple , snake_case : Optional[int] ) -> List[str]: '''simple docstring''' super().__init__() A = tokenizer A = AutoConfig.from_pretrained(snake_case ) A = TFAutoModel.from_config(snake_case ) def A_ ( self : Any , snake_case : Optional[int] ) -> Dict: '''simple docstring''' A = self.tokenizer(snake_case ) A = self.bert(**snake_case ) return out["pooler_output"] @require_tf @require_tensorflow_text class UpperCAmelCase__ ( unittest.TestCase ): def A_ ( self : int ) -> Tuple: '''simple docstring''' super().setUp() A = [ BertTokenizer.from_pretrained(snake_case ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false A = [TFBertTokenizer.from_pretrained(snake_case ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(snake_case , use_fast_bert_tokenizer=snake_case ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) A = [ 'This is a straightforward English test sentence.', 'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.', 'Now we\'re going to add some Chinese: 一 二 三 一二三', 'And some much more rare Chinese: 齉 堃 齉堃', 'Je vais aussi écrire en français pour tester les accents', 'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ', ] A = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): A = tokenizer(snake_case , return_tensors='tf' , padding='longest' ) A = tf_tokenizer(snake_case ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' for tf_tokenizer in self.tf_tokenizers: A = tf_tokenizer(self.paired_sentences ) A = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def A_ ( self : Any ) -> Tuple: '''simple docstring''' for tf_tokenizer in self.tf_tokenizers: A = tf.function(snake_case ) for test_inputs in (self.test_sentences, self.paired_sentences): A = tf.constant(snake_case ) A = compiled_tokenizer(snake_case ) A = tf_tokenizer(snake_case ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' for tf_tokenizer in self.tf_tokenizers: A = ModelToSave(tokenizer=snake_case ) A = tf.convert_to_tensor(self.test_sentences ) A = model(snake_case ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: A = Path(snake_case ) / 'saved.model' model.save(snake_case ) A = tf.keras.models.load_model(snake_case ) A = loaded_model(snake_case ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
109
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> list: UpperCamelCase = len(snake_case_ ) UpperCamelCase = [] for i in range(len(snake_case_ ) - pat_len + 1 ): UpperCamelCase = True for j in range(snake_case_ ): if s[i + j] != pattern[j]: UpperCamelCase = False break if match_found: position.append(snake_case_ ) return position if __name__ == "__main__": assert naive_pattern_search('ABCDEFG', 'DE') == [3] print(naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC'))
301
"""simple docstring""" def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str = " " ) ->list: lowerCamelCase__ : str =[] lowerCamelCase__ : int =0 for index, char in enumerate(snake_case_ ): if char == separator: split_words.append(string[last_index:index] ) lowerCamelCase__ : Dict =index + 1 elif index + 1 == len(snake_case_ ): split_words.append(string[last_index : index + 1] ) return split_words if __name__ == "__main__": from doctest import testmod testmod()
174
0
"""simple docstring""" import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): snake_case = "hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline" def __UpperCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE_ : Optional[int]=0 ): lowerCamelCase__ = np.random.RandomState(SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def __UpperCAmelCase ( self : Dict ): lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = self.get_dummy_inputs() lowerCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ).images lowerCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ = np.array([0.6_5_0_7_2, 0.5_8_4_9_2, 0.4_8_2_1_9, 0.5_5_5_2_1, 0.5_3_1_8_0, 0.5_5_9_3_9, 0.5_0_6_9_7, 0.3_9_8_0_0, 0.4_6_4_5_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCAmelCase ( self : List[Any] ): lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) lowerCamelCase__ = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = self.get_dummy_inputs() lowerCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ).images lowerCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ = np.array([0.6_5_8_6_3, 0.5_9_4_2_5, 0.4_9_3_2_6, 0.5_6_3_1_3, 0.5_3_8_7_5, 0.5_6_6_2_7, 0.5_1_0_6_5, 0.3_9_7_7_7, 0.4_6_3_3_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCAmelCase ( self : Optional[Any] ): lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) lowerCamelCase__ = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = self.get_dummy_inputs() lowerCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ).images lowerCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ = np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCAmelCase ( self : List[str] ): lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) lowerCamelCase__ = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = self.get_dummy_inputs() lowerCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ).images lowerCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ = np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCAmelCase ( self : str ): lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) lowerCamelCase__ = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = self.get_dummy_inputs() lowerCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ).images lowerCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ = np.array([0.5_3_8_1_7, 0.6_0_8_1_2, 0.4_7_3_8_4, 0.4_9_5_3_0, 0.5_1_8_9_4, 0.4_9_8_1_4, 0.4_7_9_8_4, 0.3_8_9_5_8, 0.4_4_2_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCAmelCase ( self : Any ): lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) lowerCamelCase__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = self.get_dummy_inputs() lowerCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ).images lowerCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCamelCase__ = np.array([0.5_3_8_9_5, 0.6_0_8_0_8, 0.4_7_9_3_3, 0.4_9_6_0_8, 0.5_1_8_8_6, 0.4_9_9_5_0, 0.4_8_0_5_3, 0.3_8_9_5_7, 0.4_4_2_0_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCAmelCase ( self : Optional[Any] ): lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = self.get_dummy_inputs() lowerCamelCase__ = 3 * [inputs["""prompt"""]] # forward lowerCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = output.images[0, -3:, -3:, -1] lowerCamelCase__ = self.get_dummy_inputs() lowerCamelCase__ = 3 * [inputs.pop("""prompt""" )] lowerCamelCase__ = pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" , ) lowerCamelCase__ = text_inputs["""input_ids"""] lowerCamelCase__ = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] lowerCamelCase__ = prompt_embeds # forward lowerCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 def __UpperCAmelCase ( self : Tuple ): lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = self.get_dummy_inputs() lowerCamelCase__ = 3 * ["""this is a negative prompt"""] lowerCamelCase__ = negative_prompt lowerCamelCase__ = 3 * [inputs["""prompt"""]] # forward lowerCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = output.images[0, -3:, -3:, -1] lowerCamelCase__ = self.get_dummy_inputs() lowerCamelCase__ = 3 * [inputs.pop("""prompt""" )] lowerCamelCase__ = [] for p in [prompt, negative_prompt]: lowerCamelCase__ = pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" , ) lowerCamelCase__ = text_inputs["""input_ids"""] embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] ) lowerCamelCase__ , lowerCamelCase__ = embeds # forward lowerCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 @nightly @require_onnxruntime @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @property def __UpperCAmelCase ( self : List[Any] ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __UpperCAmelCase ( self : Tuple ): lowerCamelCase__ = ort.SessionOptions() lowerCamelCase__ = False return options def __UpperCAmelCase ( self : Any ): # using the PNDM scheduler by default lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = """A painting of a squirrel eating a burger""" np.random.seed(0 ) lowerCamelCase__ = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type="""np""" ) lowerCamelCase__ = output.images lowerCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCamelCase__ = np.array([0.0_4_5_2, 0.0_3_9_0, 0.0_0_8_7, 0.0_3_5_0, 0.0_6_1_7, 0.0_3_6_4, 0.0_5_4_4, 0.0_5_2_3, 0.0_7_2_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __UpperCAmelCase ( self : List[Any] ): lowerCamelCase__ = DDIMScheduler.from_pretrained( """runwayml/stable-diffusion-v1-5""" , subfolder="""scheduler""" , revision="""onnx""" ) lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = """open neural network exchange""" lowerCamelCase__ = np.random.RandomState(0 ) lowerCamelCase__ = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=SCREAMING_SNAKE_CASE_ , output_type="""np""" ) lowerCamelCase__ = output.images lowerCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCamelCase__ = np.array([0.2_8_6_7, 0.1_9_7_4, 0.1_4_8_1, 0.7_2_9_4, 0.7_2_5_1, 0.6_6_6_7, 0.4_1_9_4, 0.5_6_4_2, 0.6_4_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __UpperCAmelCase ( self : int ): lowerCamelCase__ = LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-v1-5""" , subfolder="""scheduler""" , revision="""onnx""" ) lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = """open neural network exchange""" lowerCamelCase__ = np.random.RandomState(0 ) lowerCamelCase__ = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=SCREAMING_SNAKE_CASE_ , output_type="""np""" ) lowerCamelCase__ = output.images lowerCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCamelCase__ = np.array([0.2_3_0_6, 0.1_9_5_9, 0.1_5_9_3, 0.6_5_4_9, 0.6_3_9_4, 0.5_4_0_8, 0.5_0_6_5, 0.6_0_1_0, 0.6_1_6_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __UpperCAmelCase ( self : Union[str, Any] ): lowerCamelCase__ = 0 def test_callback_fn(SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : np.ndarray ) -> None: lowerCamelCase__ = True nonlocal number_of_steps number_of_steps += 1 if step == 0: assert latents.shape == (1, 4, 64, 64) lowerCamelCase__ = latents[0, -3:, -3:, -1] lowerCamelCase__ = np.array( [-0.6_7_7_2, -0.3_8_3_5, -1.2_4_5_6, 0.1_9_0_5, -1.0_9_7_4, 0.6_9_6_7, -1.9_3_5_3, 0.0_1_7_8, 1.0_1_6_7] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 elif step == 5: assert latents.shape == (1, 4, 64, 64) lowerCamelCase__ = latents[0, -3:, -3:, -1] lowerCamelCase__ = np.array( [-0.3_3_5_1, 0.2_2_4_1, -0.1_8_3_7, -0.2_3_2_5, -0.6_5_7_7, 0.3_3_9_3, -0.0_2_4_1, 0.5_8_9_9, 1.3_8_7_5] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 lowerCamelCase__ = False lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = """Andromeda galaxy in a bottle""" lowerCamelCase__ = np.random.RandomState(0 ) pipe( prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=5 , guidance_scale=7.5 , generator=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=1 , ) assert test_callback_fn.has_been_called assert number_of_steps == 6 def __UpperCAmelCase ( self : Any ): lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert pipe.safety_checker is None lowerCamelCase__ = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = OnnxStableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ ) # sanity check that the pipeline still works assert pipe.safety_checker is None lowerCamelCase__ = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None
258
"""simple docstring""" from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE ): def __init__( self : str , SCREAMING_SNAKE_CASE_ : Distribution , SCREAMING_SNAKE_CASE_ : Optional[int]=None , SCREAMING_SNAKE_CASE_ : Tuple=None , SCREAMING_SNAKE_CASE_ : List[str]=0 ): lowerCamelCase__ = 1.0 if scale is None else scale lowerCamelCase__ = 0.0 if loc is None else loc super().__init__(SCREAMING_SNAKE_CASE_ , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=SCREAMING_SNAKE_CASE_ )] ) @property def __UpperCAmelCase ( self : Dict ): return self.base_dist.mean * self.scale + self.loc @property def __UpperCAmelCase ( self : List[str] ): return self.base_dist.variance * self.scale**2 @property def __UpperCAmelCase ( self : int ): return self.variance.sqrt() class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Dict[str, int] , SCREAMING_SNAKE_CASE_ : Callable[..., Tuple[torch.Tensor]] , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ): super().__init__(**SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = args_dim lowerCamelCase__ = nn.ModuleList([nn.Linear(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for dim in args_dim.values()] ) lowerCamelCase__ = domain_map def __UpperCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : torch.Tensor ): lowerCamelCase__ = [proj(SCREAMING_SNAKE_CASE_ ) for proj in self.proj] return self.domain_map(*SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : Any , SCREAMING_SNAKE_CASE_ : Optional[Any] ): super().__init__() lowerCamelCase__ = function def __UpperCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Tuple , *SCREAMING_SNAKE_CASE_ : List[Any] ): return self.function(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ : snake_case = 42 snake_case = 42 snake_case = 42 def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int = 1 ): lowerCamelCase__ = dim lowerCamelCase__ = {k: dim * self.args_dim[k] for k in self.args_dim} def __UpperCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[Any] ): if self.dim == 1: return self.distribution_class(*SCREAMING_SNAKE_CASE_ ) else: return Independent(self.distribution_class(*SCREAMING_SNAKE_CASE_ ) , 1 ) def __UpperCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE_ : Optional[torch.Tensor] = None , ): lowerCamelCase__ = self._base_distribution(SCREAMING_SNAKE_CASE_ ) if loc is None and scale is None: return distr else: return AffineTransformed(SCREAMING_SNAKE_CASE_ , loc=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , event_dim=self.event_dim ) @property def __UpperCAmelCase ( self : Optional[int] ): return () if self.dim == 1 else (self.dim,) @property def __UpperCAmelCase ( self : List[Any] ): return len(self.event_shape ) @property def __UpperCAmelCase ( self : Union[str, Any] ): return 0.0 def __UpperCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : int ): return ParameterProjection( in_features=SCREAMING_SNAKE_CASE_ , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def __UpperCAmelCase ( self : Union[str, Any] , *SCREAMING_SNAKE_CASE_ : torch.Tensor ): raise NotImplementedError() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE_ : torch.Tensor ): return (x + torch.sqrt(torch.square(SCREAMING_SNAKE_CASE_ ) + 4.0 )) / 2.0 class SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE ): snake_case = {"df": 1, "loc": 1, "scale": 1} snake_case = StudentT @classmethod def __UpperCAmelCase ( cls : Dict , SCREAMING_SNAKE_CASE_ : torch.Tensor , SCREAMING_SNAKE_CASE_ : torch.Tensor , SCREAMING_SNAKE_CASE_ : torch.Tensor ): lowerCamelCase__ = cls.squareplus(SCREAMING_SNAKE_CASE_ ).clamp_min(torch.finfo(scale.dtype ).eps ) lowerCamelCase__ = 2.0 + cls.squareplus(SCREAMING_SNAKE_CASE_ ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE ): snake_case = {"loc": 1, "scale": 1} snake_case = Normal @classmethod def __UpperCAmelCase ( cls : Tuple , SCREAMING_SNAKE_CASE_ : torch.Tensor , SCREAMING_SNAKE_CASE_ : torch.Tensor ): lowerCamelCase__ = cls.squareplus(SCREAMING_SNAKE_CASE_ ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE ): snake_case = {"total_count": 1, "logits": 1} snake_case = NegativeBinomial @classmethod def __UpperCAmelCase ( cls : Union[str, Any] , SCREAMING_SNAKE_CASE_ : torch.Tensor , SCREAMING_SNAKE_CASE_ : torch.Tensor ): lowerCamelCase__ = cls.squareplus(SCREAMING_SNAKE_CASE_ ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def __UpperCAmelCase ( self : int , SCREAMING_SNAKE_CASE_ : List[Any] ): lowerCamelCase__ , lowerCamelCase__ = distr_args if self.dim == 1: return self.distribution_class(total_count=SCREAMING_SNAKE_CASE_ , logits=SCREAMING_SNAKE_CASE_ ) else: return Independent(self.distribution_class(total_count=SCREAMING_SNAKE_CASE_ , logits=SCREAMING_SNAKE_CASE_ ) , 1 ) def __UpperCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE_ : Optional[torch.Tensor] = None ): lowerCamelCase__ , lowerCamelCase__ = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
258
1
import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def lowerCamelCase__ ( __lowerCAmelCase : str ): """simple docstring""" lowerCAmelCase_ = os.path.join(args.tf_model_dir , "parameters.json" ) lowerCAmelCase_ = json.loads(open(__lowerCAmelCase ).read() ) if not params: raise ValueError( F"""It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.""" ) if not args.output.endswith(".pt" ): lowerCAmelCase_ = args.output + ".pt" lowerCAmelCase_ = OrderedDict() with tf.device("/CPU:0" ): lowerCAmelCase_ = tf.train.load_checkpoint(args.tf_model_dir ) lowerCAmelCase_ = reader.get_variable_to_shape_map() for key_name in shapes.keys(): lowerCAmelCase_ = reader.get_tensor(__lowerCAmelCase ).astype(np.floataa ) if key_name.endswith("/adam_m" ) or key_name.endswith("/adam_v" ): continue if key_name.startswith("pasts/" ): if key_name.startswith("pasts/mlp" ): lowerCAmelCase_ = int(key_name[9] ) elif key_name.startswith("pasts/out" ): lowerCAmelCase_ = 8 lowerCAmelCase_ = "model.sqout.%d.weight" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time lowerCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.startswith("model/moe" ): lowerCAmelCase_ = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/switch_gating/kernel" ): lowerCAmelCase_ = "model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player lowerCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.endswith("/softmlp/kernel" ): lowerCAmelCase_ = "model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player lowerCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.endswith("/wo/kernel" ) or key_name.endswith("/wi/kernel" ): lowerCAmelCase_ = key_name[-9:-7] for i in range(16 ): lowerCAmelCase_ = "model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer) lowerCAmelCase_ = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.startswith("model/mlp" ): lowerCAmelCase_ = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/p1/kernel" ): lowerCAmelCase_ = "model.blocks.%d.feed_forward.mlp.wi.weight" % player lowerCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.endswith("/p1/bias" ): lowerCAmelCase_ = "model.blocks.%d.feed_forward.mlp.wi.bias" % player lowerCAmelCase_ = vnp.copy() # same because it is one dimensional lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.endswith("/p2/kernel" ): lowerCAmelCase_ = "model.blocks.%d.feed_forward.mlp.wo.weight" % player lowerCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.endswith("/p2/bias" ): lowerCAmelCase_ = "model.blocks.%d.feed_forward.mlp.wo.bias" % player lowerCAmelCase_ = vnp.copy() # same because it is one dimensional lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.startswith("model/ln" ): lowerCAmelCase_ = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): lowerCAmelCase_ = "model.blocks.%d.feed_forward.norm.bias" % player lowerCAmelCase_ = vnp.copy() # same because it is one dimensional lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.endswith("/g" ): lowerCAmelCase_ = "model.blocks.%d.feed_forward.norm.weight" % player lowerCAmelCase_ = vnp.copy() # same because it is one dimensional lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.startswith("model/att" ): lowerCAmelCase_ = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/qkv/kernel" ): lowerCAmelCase_ = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum lowerCAmelCase_ = state[:, 0, :, :] lowerCAmelCase_ = state[:, 1, :, :] lowerCAmelCase_ = state[:, 2, :, :] lowerCAmelCase_ = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix lowerCAmelCase_ = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix lowerCAmelCase_ = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix lowerCAmelCase_ = "model.blocks.%d.self_attn.self_attn.q_proj.weight" % player lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) lowerCAmelCase_ = "model.blocks.%d.self_attn.self_attn.k_proj.weight" % player lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) lowerCAmelCase_ = "model.blocks.%d.self_attn.self_attn.v_proj.weight" % player lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.endswith("/o/kernel" ): lowerCAmelCase_ = "model.blocks.%d.self_attn.self_attn.out_proj.weight" % player lowerCAmelCase_ = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.startswith("model/an" ): lowerCAmelCase_ = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): lowerCAmelCase_ = "model.blocks.%d.self_attn.norm.bias" % player lowerCAmelCase_ = vnp.copy() # same because it is one dimensional lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.endswith("/g" ): lowerCAmelCase_ = "model.blocks.%d.self_attn.norm.weight" % player lowerCAmelCase_ = vnp.copy() # same because it is one dimensional lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif ( key_name.startswith("model/wte" ) or key_name.startswith("model/wpe" ) or key_name.startswith("model/ete" ) ): lowerCAmelCase_ = {"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[ key_name[-3:] ] lowerCAmelCase_ = "model.%s.weight" % nlayer lowerCAmelCase_ = vnp.copy() # same in embedded lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) if key_name.startswith("model/wte" ): lowerCAmelCase_ = "lm_head.weight" lowerCAmelCase_ = vnp.copy() # same in embedded lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name.startswith("model/wob" ): lowerCAmelCase_ = "final_logits_bias" lowerCAmelCase_ = vnp.copy() # same in embedded lowerCAmelCase_ = state.reshape((1, -1) ) lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name == "model/dense/kernel": lowerCAmelCase_ = "model.last_project.weight" lowerCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) elif key_name == "model/dense_1/bias": lowerCAmelCase_ = "model.last_project.bias" lowerCAmelCase_ = vnp.copy() # same because it is one dimensional lowerCAmelCase_ = torch.tensor(__lowerCAmelCase ) torch.save(__lowerCAmelCase , args.output ) if __name__ == "__main__": _A = argparse.ArgumentParser( description="model converter.", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("--tf_model_dir", metavar="PATH", type=str, required=True, help="import model") parser.add_argument("--output", metavar="PATH", type=str, required=True, help="output model") _A = parser.parse_args() convert_tf_gptsan_to_pt(args)
290
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging _A = logging.get_logger(__name__) _A = { "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json", "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json", "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json", "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json", "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json", "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json", } class _lowerCAmelCase ( __a ): _lowercase ='''bloom''' _lowercase =['''past_key_values'''] _lowercase ={ '''num_hidden_layers''': '''n_layer''', '''num_attention_heads''': '''n_head''', } def __init__( self , _UpperCamelCase=250_880 , _UpperCamelCase=64 , _UpperCamelCase=2 , _UpperCamelCase=8 , _UpperCamelCase=1e-5 , _UpperCamelCase=0.02 , _UpperCamelCase=True , _UpperCamelCase=1 , _UpperCamelCase=2 , _UpperCamelCase=False , _UpperCamelCase=0.0 , _UpperCamelCase=0.0 , _UpperCamelCase=1 , _UpperCamelCase=False , **_UpperCamelCase , ) -> str: lowerCAmelCase_ = vocab_size # Backward compatibility with n_embed kwarg lowerCAmelCase_ = kwargs.pop("n_embed" , _UpperCamelCase ) lowerCAmelCase_ = hidden_size if n_embed is None else n_embed lowerCAmelCase_ = n_layer lowerCAmelCase_ = n_head lowerCAmelCase_ = layer_norm_epsilon lowerCAmelCase_ = initializer_range lowerCAmelCase_ = use_cache lowerCAmelCase_ = pretraining_tp lowerCAmelCase_ = apply_residual_connection_post_layernorm lowerCAmelCase_ = hidden_dropout lowerCAmelCase_ = attention_dropout lowerCAmelCase_ = bos_token_id lowerCAmelCase_ = eos_token_id lowerCAmelCase_ = slow_but_exact super().__init__(bos_token_id=_UpperCamelCase , eos_token_id=_UpperCamelCase , **_UpperCamelCase ) class _lowerCAmelCase ( __a ): _lowercase =version.parse('''1.12''' ) def __init__( self , _UpperCamelCase , _UpperCamelCase = "default" , _UpperCamelCase = None , _UpperCamelCase = False , ) -> int: super().__init__(_UpperCamelCase , task=_UpperCamelCase , patching_specs=_UpperCamelCase , use_past=_UpperCamelCase ) if not getattr(self._config , "pad_token_id" , _UpperCamelCase ): # TODO: how to do that better? lowerCAmelCase_ = 0 @property def __a ( self ) -> Mapping[str, Mapping[int, str]]: lowerCAmelCase_ = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(_UpperCamelCase , direction="inputs" , inverted_values_shape=_UpperCamelCase ) lowerCAmelCase_ = {0: "batch", 1: "past_sequence + sequence"} else: lowerCAmelCase_ = {0: "batch", 1: "sequence"} return common_inputs @property def __a ( self ) -> int: return self._config.n_layer @property def __a ( self ) -> int: return self._config.n_head @property def __a ( self ) -> float: return 1e-3 def __a ( self , _UpperCamelCase , _UpperCamelCase = -1 , _UpperCamelCase = -1 , _UpperCamelCase = False , _UpperCamelCase = None , ) -> Mapping[str, Any]: lowerCAmelCase_ = super(_UpperCamelCase , self ).generate_dummy_inputs( _UpperCamelCase , batch_size=_UpperCamelCase , seq_length=_UpperCamelCase , is_pair=_UpperCamelCase , framework=_UpperCamelCase ) # We need to order the input in the way they appears in the forward() lowerCAmelCase_ = 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 lowerCAmelCase_ , lowerCAmelCase_ = common_inputs["input_ids"].shape # Not using the same length for past_key_values lowerCAmelCase_ = seqlen + 2 lowerCAmelCase_ = self._config.hidden_size // self.num_attention_heads lowerCAmelCase_ = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) lowerCAmelCase_ = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) lowerCAmelCase_ = [ (torch.zeros(_UpperCamelCase ), torch.zeros(_UpperCamelCase )) for _ in range(self.num_layers ) ] lowerCAmelCase_ = common_inputs["attention_mask"] if self.use_past: lowerCAmelCase_ = ordered_inputs["attention_mask"].dtype lowerCAmelCase_ = torch.cat( [ordered_inputs["attention_mask"], torch.ones(_UpperCamelCase , _UpperCamelCase , dtype=_UpperCamelCase )] , dim=1 ) return ordered_inputs @property def __a ( self ) -> int: return 13
290
1
"""simple docstring""" import heapq def __A ( a_ :dict) -> str: __a : int = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(_UpperCamelCase , [-1 * len(_UpperCamelCase), (key, value)]) # chosen_vertices = set of chosen vertices __a : Optional[Any] = set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices __a : Optional[Any] = heapq.heappop(_UpperCamelCase)[1][0] chosen_vertices.add(_UpperCamelCase) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: __a : List[str] = elem[1][1].index(_UpperCamelCase) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(_UpperCamelCase) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() A = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(F'Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}')
721
"""simple docstring""" from __future__ import annotations import typing from collections import Counter def __A ( a_ :int) -> typing.Counter[int]: __a : typing.Counter[int] = Counter() for base in range(1 , max_perimeter + 1): for perpendicular in range(a_ , max_perimeter + 1): __a : Any = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(a_): __a : List[Any] = int(base + perpendicular + hypotenuse) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def __A ( a_ :int = 10_00) -> int: __a : Dict = pythagorean_triple(a_) return triplets.most_common(1)[0][0] if __name__ == "__main__": print(F'Perimeter {solution()} has maximum solutions')
101
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/config.json''', '''umberto-commoncrawl-cased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json''' ), '''umberto-wikipedia-uncased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : Optional[Any] = "camembert" def __init__( self : Optional[Any] , __lowerCAmelCase : Any=3_0_5_2_2 , __lowerCAmelCase : List[str]=7_6_8 , __lowerCAmelCase : List[str]=1_2 , __lowerCAmelCase : Optional[int]=1_2 , __lowerCAmelCase : List[Any]=3_0_7_2 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Union[str, Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : Optional[int]=5_1_2 , __lowerCAmelCase : str=2 , __lowerCAmelCase : int=0.02 , __lowerCAmelCase : List[Any]=1E-12 , __lowerCAmelCase : Union[str, Any]=1 , __lowerCAmelCase : Optional[Any]=0 , __lowerCAmelCase : List[Any]=2 , __lowerCAmelCase : str="absolute" , __lowerCAmelCase : Any=True , __lowerCAmelCase : Optional[int]=None , **__lowerCAmelCase : Optional[int] , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Tuple = vocab_size _lowerCamelCase : str = hidden_size _lowerCamelCase : Union[str, Any] = num_hidden_layers _lowerCamelCase : Any = num_attention_heads _lowerCamelCase : Optional[Any] = hidden_act _lowerCamelCase : List[str] = intermediate_size _lowerCamelCase : Optional[Any] = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : Optional[Any] = max_position_embeddings _lowerCamelCase : Tuple = type_vocab_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : int = use_cache _lowerCamelCase : List[str] = classifier_dropout class __snake_case ( _lowercase): @property def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" if self.task == "multiple-choice": _lowerCamelCase : Optional[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _lowerCamelCase : Union[str, Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
83
class __snake_case : """simple docstring""" def __init__( self : Union[str, Any] ,lowerCAmelCase__ : str = "" ,lowerCAmelCase__ : bool = False ) -> None: '''simple docstring''' lowerCAmelCase_ : dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word lowerCAmelCase_ : Optional[int] = is_leaf lowerCAmelCase_ : List[str] = prefix def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : str ) -> tuple[str, str, str]: '''simple docstring''' lowerCAmelCase_ : List[str] = 0 for q, w in zip(self.prefix ,lowerCAmelCase__ ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : list[str] ) -> None: '''simple docstring''' for word in words: self.insert(lowerCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : str ) -> None: '''simple docstring''' if self.prefix == word: lowerCAmelCase_ : Optional[Any] = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: lowerCAmelCase_ : Optional[int] = RadixNode(prefix=lowerCAmelCase__ ,is_leaf=lowerCAmelCase__ ) else: lowerCAmelCase_ : Optional[Any] = self.nodes[word[0]] lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Any = incoming_node.match( lowerCAmelCase__ ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(lowerCAmelCase__ ) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: lowerCAmelCase_ : Dict = remaining_prefix lowerCAmelCase_ : str = self.nodes[matching_string[0]] lowerCAmelCase_ : Dict = RadixNode(lowerCAmelCase__ ,lowerCAmelCase__ ) lowerCAmelCase_ : Any = aux_node if remaining_word == "": lowerCAmelCase_ : Optional[Any] = True else: self.nodes[matching_string[0]].insert(lowerCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : str ) -> bool: '''simple docstring''' lowerCAmelCase_ : List[str] = self.nodes.get(word[0] ,lowerCAmelCase__ ) if not incoming_node: return False else: lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = incoming_node.match( lowerCAmelCase__ ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(lowerCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : str ) -> bool: '''simple docstring''' lowerCAmelCase_ : int = self.nodes.get(word[0] ,lowerCAmelCase__ ) if not incoming_node: return False else: lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = incoming_node.match( lowerCAmelCase__ ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(lowerCAmelCase__ ) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes ) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes ) == 1 and not self.is_leaf: lowerCAmelCase_ : int = list(self.nodes.values() )[0] lowerCAmelCase_ : List[Any] = merging_node.is_leaf self.prefix += merging_node.prefix lowerCAmelCase_ : int = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes ) > 1: lowerCAmelCase_ : List[str] = False # If there is 1 edge, we merge it with its child else: lowerCAmelCase_ : Union[str, Any] = list(incoming_node.nodes.values() )[0] lowerCAmelCase_ : Optional[int] = merging_node.is_leaf incoming_node.prefix += merging_node.prefix lowerCAmelCase_ : List[str] = merging_node.nodes return True def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : int = 0 ) -> None: '''simple docstring''' if self.prefix != "": print("-" * height ,self.prefix ," (leaf)" if self.is_leaf else "" ) for value in self.nodes.values(): value.print_tree(height + 1 ) def UpperCamelCase ( ): lowerCAmelCase_ : List[Any] = "banana bananas bandana band apple all beast".split() lowerCAmelCase_ : Optional[Any] = RadixNode() root.insert_many(snake_case__) assert all(root.find(snake_case__) for word in words) assert not root.find("bandanas") assert not root.find("apps") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def UpperCamelCase ( ): assert test_trie() def UpperCamelCase ( ): lowerCAmelCase_ : str = RadixNode() lowerCAmelCase_ : str = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(snake_case__) print("Words:" , snake_case__) print("Tree:") root.print_tree() if __name__ == "__main__": main()
659
0
'''simple docstring''' import sys _lowercase = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def A (__lowerCamelCase :str = N ): _lowerCAmelCase = -sys.maxsize - 1 for i in range(len(__lowerCamelCase ) - 12 ): _lowerCAmelCase = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: _lowerCAmelCase = product return largest_product if __name__ == "__main__": print(F"""{solution() = }""")
162
'''simple docstring''' from math import pi, sqrt def A (__lowerCamelCase :float ): if num <= 0: raise ValueError("""math domain error""" ) if num > 171.5: raise OverflowError("""math range error""" ) elif num - int(__lowerCamelCase ) not in (0, 0.5): raise NotImplementedError("""num must be an integer or a half-integer""" ) elif num == 0.5: return sqrt(__lowerCamelCase ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def A (): assert gamma(0.5 ) == sqrt(__lowerCamelCase ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _lowercase = 1.0 while num: _lowercase = float(input("""Gamma of: """)) print(F"""gamma({num}) = {gamma(num)}""") print("""\nEnter 0 to exit...""")
162
1
import unittest from transformers import BigBirdConfig, 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 from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class UpperCAmelCase__ ( unittest.TestCase ): def __init__( self ,A__ ,A__=2 ,A__=56 ,A__=True ,A__=True ,A__=True ,A__=True ,A__=99 ,A__=32 ,A__=2 ,A__=2 ,A__=7 ,A__="gelu_new" ,A__=0.1 ,A__=0.1 ,A__=512 ,A__=16 ,A__=2 ,A__=0.02 ,A__=4 ,A__="block_sparse" ,A__=True ,A__=False ,A__=2 ,A__=3 ,): _A : Tuple = parent _A : List[Any] = batch_size _A : Dict = seq_length _A : Tuple = is_training _A : Optional[Any] = use_attention_mask _A : Tuple = use_token_type_ids _A : Optional[int] = use_labels _A : Optional[int] = vocab_size _A : Optional[Any] = hidden_size _A : List[str] = num_hidden_layers _A : Optional[int] = num_attention_heads _A : int = intermediate_size _A : Optional[int] = hidden_act _A : Tuple = hidden_dropout_prob _A : Optional[Any] = attention_probs_dropout_prob _A : Optional[Any] = max_position_embeddings _A : List[Any] = type_vocab_size _A : Tuple = type_sequence_label_size _A : str = initializer_range _A : Any = num_choices _A : Tuple = rescale_embeddings _A : Tuple = attention_type _A : Tuple = use_bias _A : Any = block_size _A : Optional[int] = num_random_blocks def A__ ( self ): _A : List[str] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) _A : Optional[Any] = None if self.use_attention_mask: _A : int = random_attention_mask([self.batch_size, self.seq_length] ) _A : Tuple = None if self.use_token_type_ids: _A : Tuple = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) _A : Tuple = BigBirdConfig( 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 ,attention_type=self.attention_type ,block_size=self.block_size ,num_random_blocks=self.num_random_blocks ,use_bias=self.use_bias ,rescale_embeddings=self.rescale_embeddings ,) return config, input_ids, token_type_ids, attention_mask def A__ ( self ): _A : Union[str, Any] = self.prepare_config_and_inputs() _A , _A , _A , _A : List[Any] = config_and_inputs _A : Dict = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask, } return config, inputs_dict @require_flax class UpperCAmelCase__ ( __snake_case , unittest.TestCase ): __snake_case : Any = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) __snake_case : str = False __snake_case : Optional[Any] = False def A__ ( self ): _A : Dict = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def A__ ( self ): super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def A__ ( self ): super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def A__ ( self ): super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def A__ ( self ): super().test_hidden_states_output() @slow def A__ ( self ): for model_class_name in self.all_model_classes: _A : str = model_class_name.from_pretrained('''google/bigbird-roberta-base''' ) self.assertIsNotNone(A__ ) def A__ ( self ): if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def A__ ( self ): _A , _A : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _A : Dict = self._prepare_for_class(A__ ,A__ ) _A : Any = model_class(A__ ) @jax.jit def model_jitted(A__ ,A__=None ,**A__ ): return model(input_ids=A__ ,attention_mask=A__ ,**A__ ) with self.subTest('''JIT Enabled''' ): _A : Dict = model_jitted(**A__ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _A : List[str] = model_jitted(**A__ ).to_tuple() self.assertEqual(len(A__ ) ,len(A__ ) ) for jitted_output, output in zip(A__ ,A__ ): self.assertEqual(jitted_output.shape ,output.shape ) def A__ ( self ,A__ ,A__ ,A__ ,A__=1E-5 ,A__="outputs" ,A__=None ): # `bigbird_block_sparse_attention` in `FlaxBigBird` returns `attention_probs = None`, while in PyTorch version, # an effort was done to return `attention_probs` (yet to be verified). if name.startswith('''outputs.attentions''' ): return else: super().check_pt_flax_outputs(A__ ,A__ ,A__ ,A__ ,A__ ,A__ )
206
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 UpperCAmelCase__ ( __snake_case ): __snake_case : Optional[Any] = ["image_processor", "tokenizer"] __snake_case : Tuple = "BridgeTowerImageProcessor" __snake_case : List[str] = ("RobertaTokenizer", "RobertaTokenizerFast") def __init__( self ,A__ ,A__ ): super().__init__(A__ ,A__ ) def __call__( self ,A__ ,A__ = None ,A__ = True ,A__ = False ,A__ = None ,A__ = None ,A__ = 0 ,A__ = None ,A__ = None ,A__ = None ,A__ = False ,A__ = False ,A__ = False ,A__ = False ,A__ = True ,A__ = None ,**A__ ,): _A : List[Any] = self.tokenizer( text=A__ ,add_special_tokens=A__ ,padding=A__ ,truncation=A__ ,max_length=A__ ,stride=A__ ,pad_to_multiple_of=A__ ,return_token_type_ids=A__ ,return_attention_mask=A__ ,return_overflowing_tokens=A__ ,return_special_tokens_mask=A__ ,return_offsets_mapping=A__ ,return_length=A__ ,verbose=A__ ,return_tensors=A__ ,**A__ ,) # add pixel_values + pixel_mask _A : Optional[Any] = self.image_processor( A__ ,return_tensors=A__ ,do_normalize=A__ ,do_center_crop=A__ ,**A__ ) encoding.update(A__ ) return encoding def A__ ( self ,*A__ ,**A__ ): return self.tokenizer.batch_decode(*A__ ,**A__ ) def A__ ( self ,*A__ ,**A__ ): return self.tokenizer.decode(*A__ ,**A__ ) @property def A__ ( self ): _A : Union[str, Any] = self.tokenizer.model_input_names _A : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
206
1
"""simple docstring""" from math import ceil def snake_case__ ( _lowerCamelCase, _lowerCamelCase ) ->Optional[Any]: """simple docstring""" __lowercase : List[Any] = list(range(0, _lowerCamelCase ) ) __lowercase : Any = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check __lowercase : str = [] for i in device_map_blocks: if device_map_blocks.count(_lowerCamelCase ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(_lowerCamelCase ) # Missing blocks __lowercase : List[str] = [i for i in blocks if i not in device_map_blocks] __lowercase : Dict = [i for i in device_map_blocks if i not in blocks] if len(_lowerCamelCase ) != 0: raise ValueError( "Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device." " These attention blocks were specified more than once: " + str(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 0: raise ValueError( "There are attention blocks for this model that are not specified in the device_map. Add these attention " "blocks to a device on the device_map: " + str(_lowerCamelCase ) ) if len(_lowerCamelCase ) != 0: raise ValueError( "The device_map contains more attention blocks than this model has. Remove these from the device_map:" + str(_lowerCamelCase ) ) def snake_case__ ( _lowerCamelCase, _lowerCamelCase ) ->Any: """simple docstring""" __lowercase : Union[str, Any] = list(range(_lowerCamelCase ) ) __lowercase : List[str] = int(ceil(n_layers / len(_lowerCamelCase ) ) ) __lowercase : Optional[int] = [layers[i : i + n_blocks] for i in range(0, _lowerCamelCase, _lowerCamelCase )] return dict(zip(_lowerCamelCase, _lowerCamelCase ) )
718
"""simple docstring""" from __future__ import annotations def snake_case__ ( _lowerCamelCase, _lowerCamelCase = None ) ->list[list[str]]: """simple docstring""" __lowercase : List[Any] = word_bank or [] # create a table __lowercase : int = len(_lowerCamelCase ) + 1 __lowercase : list[list[list[str]]] = [] for _ in range(_lowerCamelCase ): table.append([] ) # seed value __lowercase : Any = [[]] # because empty string has empty combination # iterate through the indices for i in range(_lowerCamelCase ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(_lowerCamelCase )] == word: __lowercase : list[list[str]] = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(_lowerCamelCase )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(_lowerCamelCase )]: combination.reverse() return table[len(_lowerCamelCase )] if __name__ == "__main__": print(all_construct('jwajalapa', ['jwa', 'j', 'w', 'a', 'la', 'lapa'])) print(all_construct('rajamati', ['s', 'raj', 'amat', 'raja', 'ma', 'i', 't'])) print( all_construct( 'hexagonosaurus', ['h', 'ex', 'hex', 'ag', 'ago', 'ru', 'auru', 'rus', 'go', 'no', 'o', 's'], ) )
281
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowerCAmelCase :List[Any] = logging.get_logger(__name__) class _lowerCamelCase ( lowercase__ ): '''simple docstring''' A_ : Optional[int] = ["""input_features""", """attention_mask"""] def __init__( self : int , _A : List[Any]=80 , _A : Tuple=16000 , _A : Optional[int]=80 , _A : Dict=0.0 , _A : str=True , _A : Optional[Any]=True , _A : Dict=True , **_A : Dict , ) -> Any: super().__init__(feature_size=_A , sampling_rate=_A , padding_value=_A , **_A ) __magic_name__ : Optional[Any] = num_mel_bins __magic_name__ : Optional[int] = do_ceptral_normalize __magic_name__ : int = normalize_means __magic_name__ : Dict = normalize_vars __magic_name__ : int = True def __lowerCAmelCase ( self : str , _A : np.ndarray , ) -> np.ndarray: __magic_name__ : List[str] = waveform * (2**15) # Kaldi compliance: 16-bit signed integers __magic_name__ : Tuple = torch.from_numpy(_A ).unsqueeze(0 ) __magic_name__ : Optional[int] = ta_kaldi.fbank(_A , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def __lowerCAmelCase ( _A : np.ndarray , _A : int , _A : Optional[bool] = True , _A : Optional[bool] = True , _A : float = 0.0 , ) -> np.ndarray: # make sure we normalize float32 arrays if normalize_means: __magic_name__ : int = x[:input_length].mean(axis=0 ) __magic_name__ : Dict = np.subtract(_A , _A ) if normalize_vars: __magic_name__ : Dict = x[:input_length].std(axis=0 ) __magic_name__ : List[Any] = np.divide(_A , _A ) if input_length < x.shape[0]: __magic_name__ : Optional[int] = padding_value # make sure array is in float32 __magic_name__ : str = x.astype(np.floataa ) return x def __lowerCAmelCase ( self : Any , _A : List[np.ndarray] , _A : Optional[np.ndarray] = None ) -> List[np.ndarray]: __magic_name__ : Dict = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_A , _A , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(_A , _A ) ] def __call__( self : Tuple , _A : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , _A : Union[bool, str, PaddingStrategy] = False , _A : Optional[int] = None , _A : bool = False , _A : Optional[int] = None , _A : Optional[Union[str, TensorType]] = None , _A : Optional[int] = None , _A : Optional[bool] = None , **_A : List[Any] , ) -> BatchFeature: 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.' ) __magic_name__ : Any = 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}' ) __magic_name__ : Dict = is_batched_numpy or ( isinstance(_A , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __magic_name__ : List[str] = [np.asarray(_A , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_A , np.ndarray ): __magic_name__ : List[Any] = np.asarray(_A , dtype=np.floataa ) elif isinstance(_A , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __magic_name__ : List[str] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __magic_name__ : Any = [raw_speech] # extract fbank features __magic_name__ : Any = [self._extract_fbank_features(_A ) for waveform in raw_speech] # convert into correct format for padding __magic_name__ : int = BatchFeature({'input_features': features} ) __magic_name__ : str = 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 __magic_name__ : Optional[int] = padded_inputs.get('input_features' ) if isinstance(input_features[0] , _A ): __magic_name__ : List[str] = [np.asarray(_A , dtype=np.floataa ) for feature in input_features] __magic_name__ : Optional[Any] = padded_inputs.get('attention_mask' ) if attention_mask is not None: __magic_name__ : Dict = [np.asarray(_A , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: __magic_name__ : Dict = ( np.array(_A , dtype=np.intaa ) if self._get_padding_strategies(_A , max_length=_A ) is not PaddingStrategy.DO_NOT_PAD else None ) __magic_name__ : Dict = self.normalize( padded_inputs['input_features'] , attention_mask=_A ) if return_tensors is not None: __magic_name__ : List[Any] = padded_inputs.convert_to_tensors(_A ) return padded_inputs
561
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = ViTImageProcessor if is_vision_available() else None @property def __lowerCAmelCase ( self : str ) -> Any: return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self : List[str] ) -> Optional[Any]: __magic_name__ : Dict = (3, 32, 128) __magic_name__ : Any = tempfile.mkdtemp() # fmt: off __magic_name__ : Optional[int] = ['[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 __magic_name__ : Union[str, Any] = dict(zip(_A , range(len(_A ) ) ) ) __magic_name__ : Optional[int] = 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(_A ) + '\n' ) __magic_name__ : Tuple = { 'do_normalize': False, 'do_resize': True, 'image_processor_type': 'ViTImageProcessor', 'resample': 3, 'size': {'height': 32, 'width': 128}, } __magic_name__ : Union[str, Any] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def __lowerCAmelCase ( self : str , **_A : Optional[int] ) -> List[str]: return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_A ) def __lowerCAmelCase ( self : int , **_A : Optional[int] ) -> List[Any]: return ViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def __lowerCAmelCase ( self : Dict ) -> Tuple: shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : Dict ) -> Any: __magic_name__ : str = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) __magic_name__ : List[Any] = Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) return image_input def __lowerCAmelCase ( self : List[str] ) -> List[Any]: __magic_name__ : Union[str, Any] = self.get_tokenizer() __magic_name__ : Union[str, Any] = self.get_image_processor() __magic_name__ : List[str] = MgpstrProcessor(tokenizer=_A , image_processor=_A ) processor.save_pretrained(self.tmpdirname ) __magic_name__ : Optional[Any] = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def __lowerCAmelCase ( self : List[str] ) -> Optional[int]: __magic_name__ : int = self.get_tokenizer() __magic_name__ : int = self.get_image_processor() __magic_name__ : int = MgpstrProcessor(tokenizer=_A , image_processor=_A ) processor.save_pretrained(self.tmpdirname ) __magic_name__ : Any = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __magic_name__ : Optional[Any] = self.get_image_processor(do_normalize=_A , padding_value=1.0 ) __magic_name__ : List[str] = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[int]: __magic_name__ : Any = self.get_image_processor() __magic_name__ : Optional[Any] = self.get_tokenizer() __magic_name__ : Optional[int] = MgpstrProcessor(tokenizer=_A , image_processor=_A ) __magic_name__ : List[str] = self.prepare_image_inputs() __magic_name__ : str = image_processor(_A , return_tensors='np' ) __magic_name__ : Tuple = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: __magic_name__ : Optional[int] = self.get_image_processor() __magic_name__ : int = self.get_tokenizer() __magic_name__ : Optional[int] = MgpstrProcessor(tokenizer=_A , image_processor=_A ) __magic_name__ : Union[str, Any] = 'test' __magic_name__ : Optional[Any] = processor(text=_A ) __magic_name__ : int = tokenizer(_A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self : int ) -> int: __magic_name__ : Union[str, Any] = self.get_image_processor() __magic_name__ : str = self.get_tokenizer() __magic_name__ : List[Any] = MgpstrProcessor(tokenizer=_A , image_processor=_A ) __magic_name__ : Union[str, Any] = 'test' __magic_name__ : str = self.prepare_image_inputs() __magic_name__ : Dict = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'labels'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def __lowerCAmelCase ( self : Optional[int] ) -> Union[str, Any]: __magic_name__ : Dict = self.get_image_processor() __magic_name__ : Optional[Any] = self.get_tokenizer() __magic_name__ : Optional[Any] = MgpstrProcessor(tokenizer=_A , image_processor=_A ) __magic_name__ : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] __magic_name__ : str = processor.char_decode(_A ) __magic_name__ : Tuple = tokenizer.batch_decode(_A ) __magic_name__ : Union[str, Any] = [seq.replace(' ' , '' ) for seq in decoded_tok] self.assertListEqual(_A , _A ) def __lowerCAmelCase ( self : Optional[Any] ) -> Any: __magic_name__ : int = self.get_image_processor() __magic_name__ : Tuple = self.get_tokenizer() __magic_name__ : Any = MgpstrProcessor(tokenizer=_A , image_processor=_A ) __magic_name__ : int = None __magic_name__ : Tuple = self.prepare_image_inputs() __magic_name__ : Dict = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def __lowerCAmelCase ( self : List[str] ) -> Dict: __magic_name__ : Any = self.get_image_processor() __magic_name__ : Tuple = self.get_tokenizer() __magic_name__ : List[str] = MgpstrProcessor(tokenizer=_A , image_processor=_A ) __magic_name__ : List[str] = torch.randn(1 , 27 , 38 ) __magic_name__ : Optional[Any] = torch.randn(1 , 27 , 50257 ) __magic_name__ : Optional[int] = torch.randn(1 , 27 , 30522 ) __magic_name__ : List[Any] = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ['generated_text', 'scores', 'char_preds', 'bpe_preds', 'wp_preds'] )
561
1
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging _lowercase : Any = logging.get_logger(__name__) _lowercase : int = { "speechbrain/m-ctc-t-large": "https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json", # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class __magic_name__ ( a__): UpperCamelCase__ = '''mctct''' def __init__( self : Tuple , lowercase_ : Any=8065 , lowercase_ : int=1536 , lowercase_ : Tuple=36 , lowercase_ : int=6144 , lowercase_ : Optional[int]=4 , lowercase_ : List[Any]=384 , lowercase_ : Optional[Any]=920 , lowercase_ : int=1E-5 , lowercase_ : Tuple=0.3 , lowercase_ : List[str]="relu" , lowercase_ : Any=0.02 , lowercase_ : Optional[Any]=0.3 , lowercase_ : int=0.3 , lowercase_ : int=1 , lowercase_ : Dict=0 , lowercase_ : List[str]=2 , lowercase_ : Dict=1 , lowercase_ : List[Any]=0.3 , lowercase_ : List[Any]=1 , lowercase_ : Optional[Any]=(7,) , lowercase_ : List[str]=(3,) , lowercase_ : List[str]=80 , lowercase_ : List[Any]=1 , lowercase_ : Union[str, Any]=None , lowercase_ : Union[str, Any]="sum" , lowercase_ : Tuple=False , **lowercase_ : Optional[Any] , ): super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A ) lowercase_ : List[Any] = vocab_size lowercase_ : Optional[Any] = hidden_size lowercase_ : List[str] = num_hidden_layers lowercase_ : Union[str, Any] = intermediate_size lowercase_ : List[str] = num_attention_heads lowercase_ : Optional[Any] = attention_head_dim lowercase_ : Optional[int] = max_position_embeddings lowercase_ : List[str] = layer_norm_eps lowercase_ : Dict = layerdrop lowercase_ : Optional[Any] = hidden_act lowercase_ : Tuple = initializer_range lowercase_ : Optional[int] = hidden_dropout_prob lowercase_ : Dict = attention_probs_dropout_prob lowercase_ : Union[str, Any] = pad_token_id lowercase_ : Any = bos_token_id lowercase_ : Union[str, Any] = eos_token_id lowercase_ : str = conv_glu_dim lowercase_ : int = conv_dropout lowercase_ : str = num_conv_layers lowercase_ : Union[str, Any] = input_feat_per_channel lowercase_ : Any = input_channels lowercase_ : Optional[int] = conv_channels lowercase_ : str = ctc_loss_reduction lowercase_ : str = ctc_zero_infinity # prevents config testing fail with exporting to json lowercase_ : Any = list(_A ) lowercase_ : List[Any] = list(_A ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ f'''but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, ''' f'''`config.num_conv_layers = {self.num_conv_layers}`.''' )
716
'''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=_UpperCAmelCase) class __magic_name__ ( _UpperCAmelCase): UpperCamelCase__ = field(default='''image-classification''', metadata={'''include_in_asdict_even_if_is_default''': True}) UpperCamelCase__ = Features({'''image''': Image()}) UpperCamelCase__ = Features({'''labels''': ClassLabel}) UpperCamelCase__ = "image" UpperCamelCase__ = "labels" def SCREAMING_SNAKE_CASE_ ( self : Tuple , lowercase_ : str ): 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] , lowercase_ ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) lowercase_ : List[str] = copy.deepcopy(self ) lowercase_ : List[str] = self.label_schema.copy() lowercase_ : List[Any] = features[self.label_column] lowercase_ : Optional[Any] = label_schema return task_template @property def SCREAMING_SNAKE_CASE_ ( self : int ): return { self.image_column: "image", self.label_column: "labels", }
30
0
from collections.abc import Sequence def lowerCAmelCase_ ( __UpperCAmelCase: Sequence[float] , __UpperCAmelCase: bool = False ) -> float: if not arr: return 0 UpperCamelCase__ : Union[str, Any] = 0 if allow_empty_subarrays else float('''-inf''' ) UpperCamelCase__ : Optional[int] = 0.0 for num in arr: UpperCamelCase__ : List[Any] = max(0 if allow_empty_subarrays else num , curr_sum + num ) UpperCamelCase__ : str = max(__UpperCAmelCase , __UpperCAmelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase_ = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(F'''{max_subarray_sum(nums) = }''')
253
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase__ : '''simple docstring''' def __init__( self, __magic_name__, __magic_name__=3, __magic_name__=32, __magic_name__=3, __magic_name__=10, __magic_name__=[10, 20, 30, 40], __magic_name__=[1, 1, 2, 1], __magic_name__=True, __magic_name__=True, __magic_name__="relu", __magic_name__=3, __magic_name__=None, ) -> Optional[Any]: """simple docstring""" UpperCamelCase__ : Optional[Any] = parent UpperCamelCase__ : Tuple = batch_size UpperCamelCase__ : int = image_size UpperCamelCase__ : Tuple = num_channels UpperCamelCase__ : Union[str, Any] = embeddings_size UpperCamelCase__ : Dict = hidden_sizes UpperCamelCase__ : Any = depths UpperCamelCase__ : List[str] = is_training UpperCamelCase__ : Optional[int] = use_labels UpperCamelCase__ : Optional[int] = hidden_act UpperCamelCase__ : List[Any] = num_labels UpperCamelCase__ : Optional[int] = scope UpperCamelCase__ : int = len(__magic_name__ ) def UpperCamelCase__ ( self ) -> Dict: """simple docstring""" UpperCamelCase__ : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ : List[str] = None if self.use_labels: UpperCamelCase__ : Dict = ids_tensor([self.batch_size], self.num_labels ) UpperCamelCase__ : Dict = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( self ) -> Any: """simple docstring""" return ResNetConfig( num_channels=self.num_channels, embeddings_size=self.embeddings_size, hidden_sizes=self.hidden_sizes, depths=self.depths, hidden_act=self.hidden_act, num_labels=self.num_labels, image_size=self.image_size, ) def UpperCamelCase__ ( self, __magic_name__, __magic_name__, __magic_name__ ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ : str = TFResNetModel(config=__magic_name__ ) UpperCamelCase__ : Dict = model(__magic_name__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32), ) def UpperCamelCase__ ( self, __magic_name__, __magic_name__, __magic_name__ ) -> Any: """simple docstring""" UpperCamelCase__ : int = self.num_labels UpperCamelCase__ : List[Any] = TFResNetForImageClassification(__magic_name__ ) UpperCamelCase__ : int = model(__magic_name__, labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def UpperCamelCase__ ( self ) -> str: """simple docstring""" UpperCamelCase__ : List[Any] = self.prepare_config_and_inputs() UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ : Any = config_and_inputs UpperCamelCase__ : Dict = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class lowercase__ ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): '''simple docstring''' a : Optional[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () a : Optional[int] = ( {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification} if is_tf_available() else {} ) a : int = False a : List[str] = False a : Optional[Any] = False a : Tuple = False a : List[str] = False def UpperCamelCase__ ( self ) -> Dict: """simple docstring""" UpperCamelCase__ : Tuple = TFResNetModelTester(self ) UpperCamelCase__ : Tuple = ConfigTester(self, config_class=__magic_name__, has_text_modality=__magic_name__ ) def UpperCamelCase__ ( self ) -> Union[str, Any]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase__ ( self ) -> int: """simple docstring""" return @unittest.skip(reason='''ResNet does not use inputs_embeds''' ) def UpperCamelCase__ ( self ) -> List[str]: """simple docstring""" pass @unittest.skip(reason='''ResNet does not support input and output embeddings''' ) def UpperCamelCase__ ( self ) -> List[str]: """simple docstring""" pass def UpperCamelCase__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase__ ,UpperCamelCase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ : Tuple = model_class(__magic_name__ ) UpperCamelCase__ : List[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ : Dict = [*signature.parameters.keys()] UpperCamelCase__ : Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1], __magic_name__ ) def UpperCamelCase__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCamelCase__ ( self ) -> Tuple: """simple docstring""" def check_hidden_states_output(__magic_name__, __magic_name__, __magic_name__ ): UpperCamelCase__ : List[str] = model_class(__magic_name__ ) UpperCamelCase__ : Optional[Any] = model(**self._prepare_for_class(__magic_name__, __magic_name__ ) ) UpperCamelCase__ : Optional[int] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase__ : Tuple = self.model_tester.num_stages self.assertEqual(len(__magic_name__ ), expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [self.model_tester.image_size // 4, self.model_tester.image_size // 4], ) UpperCamelCase__ ,UpperCamelCase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ : int = ['''basic''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: UpperCamelCase__ : Any = layer_type UpperCamelCase__ : Union[str, Any] = True check_hidden_states_output(__magic_name__, __magic_name__, __magic_name__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase__ : Any = True check_hidden_states_output(__magic_name__, __magic_name__, __magic_name__ ) def UpperCamelCase__ ( self ) -> int: """simple docstring""" UpperCamelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__magic_name__ ) @slow def UpperCamelCase__ ( self ) -> Tuple: """simple docstring""" for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ : Any = TFResNetModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def lowerCAmelCase_ ( ) -> List[Any]: UpperCamelCase__ : Optional[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class lowercase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ ( self ) -> Dict: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCamelCase__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ : List[Any] = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCamelCase__ : Any = self.default_image_processor UpperCamelCase__ : str = prepare_img() UpperCamelCase__ : Union[str, Any] = image_processor(images=__magic_name__, return_tensors='''tf''' ) # forward pass UpperCamelCase__ : str = model(**__magic_name__ ) # verify the logits UpperCamelCase__ : Union[str, Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape, __magic_name__ ) UpperCamelCase__ : List[Any] = tf.constant([-11.1069, -9.7877, -8.3777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy(), __magic_name__, atol=1E-4 ) )
253
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __SCREAMING_SNAKE_CASE ( __A , __A , __A , unittest.TestCase): __SCREAMING_SNAKE_CASE : Optional[Any] = AltDiffusionPipeline __SCREAMING_SNAKE_CASE : int = TEXT_TO_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS __SCREAMING_SNAKE_CASE : str = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS def UpperCAmelCase__ ( self : str ): torch.manual_seed(0 ) _UpperCAmelCase = 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 , ) _UpperCAmelCase = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCamelCase__ , set_alpha_to_one=UpperCamelCase__ , ) torch.manual_seed(0 ) _UpperCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) # TODO: address the non-deterministic text encoder (fails for save-load tests) # torch.manual_seed(0) # text_encoder_config = RobertaSeriesConfig( # hidden_size=32, # project_dim=32, # intermediate_size=37, # layer_norm_eps=1e-05, # num_attention_heads=4, # num_hidden_layers=5, # vocab_size=5002, # ) # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config) torch.manual_seed(0 ) _UpperCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_002 , ) _UpperCAmelCase = CLIPTextModel(UpperCamelCase__ ) _UpperCAmelCase = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) _UpperCAmelCase = 77 _UpperCAmelCase = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def UpperCAmelCase__ ( self : str , __UpperCamelCase : List[str] , __UpperCamelCase : Union[str, Any]=0 ): if str(UpperCamelCase__ ).startswith("mps" ): _UpperCAmelCase = torch.manual_seed(UpperCamelCase__ ) else: _UpperCAmelCase = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) _UpperCAmelCase = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def UpperCAmelCase__ ( self : List[Any] ): super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 ) def UpperCAmelCase__ ( self : str ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def UpperCAmelCase__ ( self : str ): _UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator _UpperCAmelCase = self.get_dummy_components() torch.manual_seed(0 ) _UpperCAmelCase = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_002 , ) # TODO: remove after fixing the non-deterministic text encoder _UpperCAmelCase = RobertaSeriesModelWithTransformation(UpperCamelCase__ ) _UpperCAmelCase = text_encoder _UpperCAmelCase = AltDiffusionPipeline(**UpperCamelCase__ ) _UpperCAmelCase = alt_pipe.to(UpperCamelCase__ ) alt_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) _UpperCAmelCase = self.get_dummy_inputs(UpperCamelCase__ ) _UpperCAmelCase = 'A photo of an astronaut' _UpperCAmelCase = alt_pipe(**UpperCamelCase__ ) _UpperCAmelCase = output.images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCAmelCase = np.array( [0.5748162, 0.60447145, 0.48821217, 0.50100636, 0.5431185, 0.45763683, 0.49657696, 0.48132733, 0.47573093] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase__ ( self : Union[str, Any] ): _UpperCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = PNDMScheduler(skip_prk_steps=UpperCamelCase__ ) torch.manual_seed(0 ) _UpperCAmelCase = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_002 , ) # TODO: remove after fixing the non-deterministic text encoder _UpperCAmelCase = RobertaSeriesModelWithTransformation(UpperCamelCase__ ) _UpperCAmelCase = text_encoder _UpperCAmelCase = AltDiffusionPipeline(**UpperCamelCase__ ) _UpperCAmelCase = alt_pipe.to(UpperCamelCase__ ) alt_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) _UpperCAmelCase = self.get_dummy_inputs(UpperCamelCase__ ) _UpperCAmelCase = alt_pipe(**UpperCamelCase__ ) _UpperCAmelCase = output.images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCAmelCase = np.array( [0.51605093, 0.5707241, 0.47365507, 0.50578886, 0.5633877, 0.4642503, 0.5182081, 0.48763484, 0.49084237] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase): def UpperCAmelCase__ ( self : List[str] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : Optional[int] ): # make sure here that pndm scheduler skips prk _UpperCAmelCase = AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion" , safety_checker=UpperCamelCase__ ) _UpperCAmelCase = alt_pipe.to(UpperCamelCase__ ) alt_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) _UpperCAmelCase = 'A painting of a squirrel eating a burger' _UpperCAmelCase = torch.manual_seed(0 ) _UpperCAmelCase = alt_pipe([prompt] , generator=UpperCamelCase__ , guidance_scale=6.0 , num_inference_steps=20 , output_type="np" ) _UpperCAmelCase = output.images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _UpperCAmelCase = np.array([0.1010, 0.0800, 0.0794, 0.0885, 0.0843, 0.0762, 0.0769, 0.0729, 0.0586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase__ ( self : Dict ): _UpperCAmelCase = DDIMScheduler.from_pretrained("BAAI/AltDiffusion" , subfolder="scheduler" ) _UpperCAmelCase = AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion" , scheduler=UpperCamelCase__ , safety_checker=UpperCamelCase__ ) _UpperCAmelCase = alt_pipe.to(UpperCamelCase__ ) alt_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) _UpperCAmelCase = 'A painting of a squirrel eating a burger' _UpperCAmelCase = torch.manual_seed(0 ) _UpperCAmelCase = alt_pipe([prompt] , generator=UpperCamelCase__ , num_inference_steps=2 , output_type="numpy" ) _UpperCAmelCase = output.images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _UpperCAmelCase = np.array([0.4019, 0.4052, 0.3810, 0.4119, 0.3916, 0.3982, 0.4651, 0.4195, 0.5323] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
709
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": __lowerCAmelCase = pd.read_csv("sample_data.csv", header=None) __lowerCAmelCase = df.shape[:1][0] # If you're using some other dataset input the target column __lowerCAmelCase = df.iloc[:, 1:2] __lowerCAmelCase = actual_data.values.reshape(len_data, 1) __lowerCAmelCase = MinMaxScaler().fit_transform(actual_data) __lowerCAmelCase = 1_0 __lowerCAmelCase = 5 __lowerCAmelCase = 2_0 __lowerCAmelCase = len_data - periods * look_back __lowerCAmelCase = actual_data[:division] __lowerCAmelCase = actual_data[division - look_back :] __lowerCAmelCase , __lowerCAmelCase = [], [] __lowerCAmelCase , __lowerCAmelCase = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) __lowerCAmelCase = np.array(train_x) __lowerCAmelCase = np.array(test_x) __lowerCAmelCase = np.array([list(i.ravel()) for i in train_y]) __lowerCAmelCase = np.array([list(i.ravel()) for i in test_y]) __lowerCAmelCase = Sequential() model.add(LSTM(1_2_8, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(6_4, input_shape=(1_2_8, 1))) model.add(Dense(forward_days)) model.compile(loss="mean_squared_error", optimizer="adam") __lowerCAmelCase = model.fit( x_train, y_train, epochs=1_5_0, verbose=1, shuffle=True, batch_size=4 ) __lowerCAmelCase = model.predict(x_test)
129
0
from PIL import Image def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Image: """simple docstring""" def brightness(snake_case_ ) -> float: return 1_2_8 + level + (c - 1_2_8) if not -255.0 <= level <= 255.0: raise ValueError('''level must be between -255.0 (black) and 255.0 (white)''' ) return img.point(lowerCAmelCase__ ) if __name__ == "__main__": # Load image with Image.open("""image_data/lena.jpg""") as img: # Change brightness to 100 UpperCamelCase__ : Tuple = change_brightness(img, 100) brigt_img.save("""image_data/lena_brightness.png""", format="""png""")
387
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class _A ( lowerCAmelCase ): snake_case__ : List[Any] = 'philschmid/bart-large-cnn-samsum' snake_case__ : int = ( 'This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, ' 'and returns a summary of the text.' ) snake_case__ : Tuple = 'summarizer' snake_case__ : int = AutoTokenizer snake_case__ : Any = AutoModelForSeqaSeqLM snake_case__ : Optional[int] = ['text'] snake_case__ : Optional[int] = ['text'] def A__ ( self , __lowerCAmelCase ): """simple docstring""" return self.pre_processor(__lowerCAmelCase , return_tensors="""pt""" , truncation=__lowerCAmelCase ) def A__ ( self , __lowerCAmelCase ): """simple docstring""" return self.model.generate(**__lowerCAmelCase )[0] def A__ ( self , __lowerCAmelCase ): """simple docstring""" return self.pre_processor.decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase )
359
0
'''simple docstring''' from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ): '''simple docstring''' if version.parse(hfh.__version__ ).release < version.parse("""0.11.0""" ).release: # old versions of hfh don't url-encode the file path A_ : str = quote(__lowerCAmelCase ) return hfh.hf_hub_url(__lowerCAmelCase , __lowerCAmelCase , repo_type="""dataset""" , revision=__lowerCAmelCase )
718
'''simple docstring''' import pytest lowerCamelCase :Optional[Any] = '''__dummy_dataset1__''' lowerCamelCase :List[Any] = ''' import json import os import datasets REPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/" URLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"} class __DummyDataset1__(datasets.GeneratorBasedBuilder): def _info(self): features = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "ner_tags": datasets.Sequence( datasets.features.ClassLabel( names=[ "O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", ] ) ), "langs": datasets.Sequence(datasets.Value("string")), "spans": datasets.Sequence(datasets.Value("string")), } ) return datasets.DatasetInfo(features=features) def _split_generators(self, dl_manager): dl_path = dl_manager.download(URLS) return [ datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}), datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}), ] def _generate_examples(self, filepath): with open(filepath, "r", encoding="utf-8") as f: for i, line in enumerate(f): yield i, json.loads(line) ''' @pytest.fixture def a ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def a ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' A_ : List[str] = dataset_loading_script_name A_ : int = tmp_path / """datasets""" / script_name script_dir.mkdir(parents=lowerCamelCase__ ) A_ : Tuple = script_dir / f'{script_name}.py' with open(lowerCamelCase__ , """w""" ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ )
686
0
def lowercase__ ( __snake_case : list , __snake_case : list ): '''simple docstring''' _validate_point(__snake_case ) _validate_point(__snake_case ) if len(__snake_case ) != len(__snake_case ): raise ValueError('Both points must be in the same n-dimensional space' ) return float(sum(abs(a - b ) for a, b in zip(__snake_case , __snake_case ) ) ) def lowercase__ ( __snake_case : list[float] ): '''simple docstring''' if point: if isinstance(__snake_case , __snake_case ): for item in point: if not isinstance(__snake_case , (int, float) ): UpperCAmelCase_ : Optional[int] = ( 'Expected a list of numbers as input, found ' F"{type(__snake_case ).__name__}" ) raise TypeError(__snake_case ) else: UpperCAmelCase_ : int = F"Expected a list of numbers as input, found {type(__snake_case ).__name__}" raise TypeError(__snake_case ) else: raise ValueError('Missing an input' ) def lowercase__ ( __snake_case : list , __snake_case : list ): '''simple docstring''' _validate_point(__snake_case ) _validate_point(__snake_case ) if len(__snake_case ) != len(__snake_case ): raise ValueError('Both points must be in the same n-dimensional space' ) return float(sum(abs(x - y ) for x, y in zip(__snake_case , __snake_case ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
406
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCamelCase (_snake_case ): '''simple docstring''' _snake_case : Tuple = ['''image_processor''', '''tokenizer'''] _snake_case : Any = '''ViTImageProcessor''' _snake_case : str = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self , _UpperCamelCase=None , _UpperCamelCase=None , **_UpperCamelCase ) -> Optional[int]: UpperCAmelCase_ : int = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , _UpperCamelCase , ) UpperCAmelCase_ : str = kwargs.pop('feature_extractor' ) UpperCAmelCase_ : Optional[int] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(_UpperCamelCase , _UpperCamelCase ) def __call__( self , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=None , **_UpperCamelCase ) -> Optional[Any]: if text is None and visual_prompt is None and images is None: raise ValueError('You have to specify either text, visual prompt or images.' ) if text is not None and visual_prompt is not None: raise ValueError('You have to specify exactly one type of prompt. Either text or visual prompt.' ) if text is not None: UpperCAmelCase_ : int = self.tokenizer(_UpperCamelCase , return_tensors=_UpperCamelCase , **_UpperCamelCase ) if visual_prompt is not None: UpperCAmelCase_ : str = self.image_processor(_UpperCamelCase , return_tensors=_UpperCamelCase , **_UpperCamelCase ) if images is not None: UpperCAmelCase_ : Union[str, Any] = self.image_processor(_UpperCamelCase , return_tensors=_UpperCamelCase , **_UpperCamelCase ) if visual_prompt is not None and images is not None: UpperCAmelCase_ : Tuple = { 'pixel_values': image_features.pixel_values, 'conditional_pixel_values': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: UpperCAmelCase_ : List[Any] = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: UpperCAmelCase_ : Optional[Any] = { 'conditional_pixel_values': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**_UpperCamelCase ) , tensor_type=_UpperCamelCase ) def __UpperCAmelCase ( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: return self.tokenizer.batch_decode(*_UpperCamelCase , **_UpperCamelCase ) def __UpperCAmelCase ( self , *_UpperCamelCase , **_UpperCamelCase ) -> int: return self.tokenizer.decode(*_UpperCamelCase , **_UpperCamelCase ) @property def __UpperCAmelCase ( self ) -> List[Any]: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _UpperCamelCase , ) return self.image_processor_class @property def __UpperCAmelCase ( self ) -> int: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _UpperCamelCase , ) return self.image_processor
406
1
from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline __SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) class lowercase_ ( lowerCamelCase__ ): def UpperCamelCase ( self , lowercase_ ): if isinstance(__lowerCamelCase , __lowerCamelCase ): _snake_case : Dict = [label.strip() for label in labels.split("," ) if label.strip()] return labels def __call__( self , lowercase_ , lowercase_ , lowercase_ ): if len(__lowerCamelCase ) == 0 or len(__lowerCamelCase ) == 0: raise ValueError("You must include at least one label and at least one sequence." ) if hypothesis_template.format(labels[0] ) == hypothesis_template: raise ValueError( ( "The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. " "Make sure the passed template includes formatting syntax such as {{}} where the label should go." ).format(__lowerCamelCase ) ) if isinstance(__lowerCamelCase , __lowerCamelCase ): _snake_case : Optional[Any] = [sequences] _snake_case : Tuple = [] for sequence in sequences: sequence_pairs.extend([[sequence, hypothesis_template.format(__lowerCamelCase )] for label in labels] ) return sequence_pairs, sequences @add_end_docstrings(lowerCamelCase__ ) class lowercase_ ( lowerCamelCase__ ): def __init__( self , lowercase_=ZeroShotClassificationArgumentHandler() , *lowercase_ , **lowercase_ ): _snake_case : Optional[int] = args_parser super().__init__(*__lowerCamelCase , **__lowerCamelCase ) if self.entailment_id == -1: logger.warning( "Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to " "-1. Define a descriptive label2id mapping in the model config to ensure correct outputs." ) @property def UpperCamelCase ( self ): for label, ind in self.model.config.labelaid.items(): if label.lower().startswith("entail" ): return ind return -1 def UpperCamelCase ( self , lowercase_ , lowercase_=True , lowercase_=True , lowercase_=TruncationStrategy.ONLY_FIRST , **lowercase_ ): _snake_case : Dict = self.framework if self.tokenizer.pad_token is None: # Override for tokenizers not supporting padding logger.error( "Tokenizer was not supporting padding necessary for zero-shot, attempting to use " " `pad_token=eos_token`" ) _snake_case : List[Any] = self.tokenizer.eos_token try: _snake_case : str = self.tokenizer( __lowerCamelCase , add_special_tokens=__lowerCamelCase , return_tensors=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , ) except Exception as e: if "too short" in str(__lowerCamelCase ): # tokenizers might yell that we want to truncate # to a value that is not even reached by the input. # In that case we don't want to truncate. # It seems there's not a really better way to catch that # exception. _snake_case : Optional[int] = self.tokenizer( __lowerCamelCase , add_special_tokens=__lowerCamelCase , return_tensors=__lowerCamelCase , padding=__lowerCamelCase , truncation=TruncationStrategy.DO_NOT_TRUNCATE , ) else: raise e return inputs def UpperCamelCase ( self , **lowercase_ ): if kwargs.get("multi_class" , __lowerCamelCase ) is not None: _snake_case : Tuple = kwargs['''multi_class'''] logger.warning( "The `multi_class` argument has been deprecated and renamed to `multi_label`. " "`multi_class` will be removed in a future version of Transformers." ) _snake_case : Tuple = {} if "candidate_labels" in kwargs: _snake_case : Dict = self._args_parser._parse_labels(kwargs["candidate_labels"] ) if "hypothesis_template" in kwargs: _snake_case : List[str] = kwargs['''hypothesis_template'''] _snake_case : Tuple = {} if "multi_label" in kwargs: _snake_case : List[Any] = kwargs['''multi_label'''] return preprocess_params, {}, postprocess_params def __call__( self , lowercase_ , *lowercase_ , **lowercase_ , ): if len(__lowerCamelCase ) == 0: pass elif len(__lowerCamelCase ) == 1 and "candidate_labels" not in kwargs: _snake_case : Union[str, Any] = args[0] else: raise ValueError(f"""Unable to understand extra arguments {args}""" ) return super().__call__(__lowerCamelCase , **__lowerCamelCase ) def UpperCamelCase ( self , lowercase_ , lowercase_=None , lowercase_="This example is {}." ): _snake_case : int = self._args_parser(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) for i, (candidate_label, sequence_pair) in enumerate(zip(__lowerCamelCase , __lowerCamelCase ) ): _snake_case : Optional[int] = self._parse_and_tokenize([sequence_pair] ) yield { "candidate_label": candidate_label, "sequence": sequences[0], "is_last": i == len(__lowerCamelCase ) - 1, **model_input, } def UpperCamelCase ( self , lowercase_ ): _snake_case : Any = inputs['''candidate_label'''] _snake_case : List[Any] = inputs['''sequence'''] _snake_case : Dict = {k: inputs[k] for k in self.tokenizer.model_input_names} _snake_case : List[str] = self.model(**__lowerCamelCase ) _snake_case : Any = { '''candidate_label''': candidate_label, '''sequence''': sequence, '''is_last''': inputs['''is_last'''], **outputs, } return model_outputs def UpperCamelCase ( self , lowercase_ , lowercase_=False ): _snake_case : Optional[int] = [outputs['''candidate_label'''] for outputs in model_outputs] _snake_case : int = [outputs['''sequence'''] for outputs in model_outputs] _snake_case : Dict = np.concatenate([output["logits"].numpy() for output in model_outputs] ) _snake_case : List[str] = logits.shape[0] _snake_case : Optional[int] = len(__lowerCamelCase ) _snake_case : List[Any] = N // n _snake_case : List[str] = logits.reshape((num_sequences, n, -1) ) if multi_label or len(__lowerCamelCase ) == 1: # softmax over the entailment vs. contradiction dim for each label independently _snake_case : Optional[Any] = self.entailment_id _snake_case : List[str] = -1 if entailment_id == 0 else 0 _snake_case : Optional[Any] = reshaped_outputs[..., [contradiction_id, entailment_id]] _snake_case : Dict = np.exp(__lowerCamelCase ) / np.exp(__lowerCamelCase ).sum(-1 , keepdims=__lowerCamelCase ) _snake_case : List[Any] = scores[..., 1] else: # softmax the "entailment" logits over all candidate labels _snake_case : List[Any] = reshaped_outputs[..., self.entailment_id] _snake_case : str = np.exp(__lowerCamelCase ) / np.exp(__lowerCamelCase ).sum(-1 , keepdims=__lowerCamelCase ) _snake_case : List[Any] = list(reversed(scores[0].argsort() ) ) return { "sequence": sequences[0], "labels": [candidate_labels[i] for i in top_inds], "scores": scores[0, top_inds].tolist(), }
702
import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class lowercase_ ( datasets.BuilderConfig ): _lowerCamelCase = None class lowercase_ ( datasets.ArrowBasedBuilder ): _lowerCamelCase = PandasConfig def UpperCamelCase ( self ): return datasets.DatasetInfo(features=self.config.features ) def UpperCamelCase ( self , lowercase_ ): if not self.config.data_files: raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) _snake_case : Any = dl_manager.download_and_extract(self.config.data_files ) if isinstance(lowercase_ , (str, list, tuple) ): _snake_case : str = data_files if isinstance(lowercase_ , lowercase_ ): _snake_case : int = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _snake_case : Optional[Any] = [dl_manager.iter_files(lowercase_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )] _snake_case : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(lowercase_ , lowercase_ ): _snake_case : Tuple = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _snake_case : int = [dl_manager.iter_files(lowercase_ ) for file in files] splits.append(datasets.SplitGenerator(name=lowercase_ , gen_kwargs={"files": files} ) ) return splits def UpperCamelCase ( self , lowercase_ ): if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example _snake_case : str = table_cast(lowercase_ , self.config.features.arrow_schema ) return pa_table def UpperCamelCase ( self , lowercase_ ): for i, file in enumerate(itertools.chain.from_iterable(lowercase_ ) ): with open(lowercase_ , "rb" ) as f: _snake_case : Dict = pa.Table.from_pandas(pd.read_pickle(lowercase_ ) ) yield i, self._cast_table(lowercase_ )
580
0
"""simple docstring""" class UpperCamelCase_ (__A ): pass class UpperCamelCase_ (__A ): pass class UpperCamelCase_ : def __init__( self : List[str] ) -> Tuple: UpperCAmelCase_ : int = [ [], [], [], ] def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : int ) -> None: try: if len(self.queues[priority] ) >= 100: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(lowerCAmelCase_ ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def _SCREAMING_SNAKE_CASE ( self : str ) -> int: for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self : int ) -> str: return "\n".join(f"""Priority {i}: {q}""" for i, q in enumerate(self.queues ) ) class UpperCamelCase_ : def __init__( self : int ) -> Union[str, Any]: UpperCAmelCase_ : Tuple = [] def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase_ : int ) -> None: if len(self.queue ) == 100: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : str ) -> int: if not self.queue: raise UnderFlowError("The queue is empty" ) else: UpperCAmelCase_ : Union[str, Any] = min(self.queue ) self.queue.remove(lowerCAmelCase_ ) return data def __str__( self : Dict ) -> str: return str(self.queue ) def snake_case ( ): UpperCAmelCase_ : Dict = FixedPriorityQueue() fpq.enqueue(0 ,10 ) fpq.enqueue(1 ,70 ) fpq.enqueue(0 ,1_00 ) fpq.enqueue(2 ,1 ) fpq.enqueue(2 ,5 ) fpq.enqueue(1 ,7 ) fpq.enqueue(2 ,4 ) fpq.enqueue(1 ,64 ) fpq.enqueue(0 ,1_28 ) print(A__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(A__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def snake_case ( ): UpperCAmelCase_ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(A__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(A__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
95
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _lowerCamelCase ( lowercase : Any ) -> List[str]: return getitem, k def _lowerCamelCase ( lowercase : Optional[Any] , lowercase : Union[str, Any] ) -> Any: return setitem, k, v def _lowerCamelCase ( lowercase : int ) -> Union[str, Any]: return delitem, k def _lowerCamelCase ( lowercase : Tuple , lowercase : Dict , *lowercase : Union[str, Any] ) -> int: try: return fun(lowercase , *lowercase ), None except Exception as e: return None, e lowerCAmelCase_ : Optional[Any] = ( _set('key_a', 'val_a'), _set('key_b', 'val_b'), ) lowerCAmelCase_ : Optional[int] = [ _set('key_a', 'val_a'), _set('key_a', 'val_b'), ] lowerCAmelCase_ : int = [ _set('key_a', 'val_a'), _set('key_b', 'val_b'), _del('key_a'), _del('key_b'), _set('key_a', 'val_a'), _del('key_a'), ] lowerCAmelCase_ : List[Any] = [ _get('key_a'), _del('key_a'), _set('key_a', 'val_a'), _del('key_a'), _del('key_a'), _get('key_a'), ] lowerCAmelCase_ : str = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowerCAmelCase_ : str = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('key_a', 'val_b'), ] @pytest.mark.parametrize( "operations" , ( pytest.param(_add_items , id="add items" ), pytest.param(_overwrite_items , id="overwrite items" ), pytest.param(_delete_items , id="delete items" ), pytest.param(_access_absent_items , id="access absent items" ), pytest.param(_add_with_resize_up , id="add with resize up" ), pytest.param(_add_with_resize_down , id="add with resize down" ), ) , ) def _lowerCamelCase ( lowercase : Optional[int] ) -> Optional[int]: _a = HashMap(initial_block_size=4 ) _a = {} for _, (fun, *args) in enumerate(lowercase ): _a , _a = _run_operation(lowercase , lowercase , *lowercase ) _a , _a = _run_operation(lowercase , lowercase , *lowercase ) assert my_res == py_res assert str(lowercase ) == str(lowercase ) assert set(lowercase ) == set(lowercase ) assert len(lowercase ) == len(lowercase ) assert set(my.items() ) == set(py.items() ) def _lowerCamelCase ( ) -> str: def is_public(lowercase : str ) -> bool: return not name.startswith("_" ) _a = {name for name in dir({} ) if is_public(lowercase )} _a = {name for name in dir(HashMap() ) if is_public(lowercase )} assert dict_public_names > hash_public_names
692
0
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def snake_case_ ( __lowercase ): UpperCAmelCase_ : Any = filter(lambda __lowercase : p.requires_grad , model.parameters() ) UpperCAmelCase_ : Optional[Any] = sum([np.prod(p.size() ) for p in model_parameters] ) return params __UpperCamelCase : Dict = logging.getLogger(__name__) def snake_case_ ( __lowercase , __lowercase ): if metric == "rouge2": UpperCAmelCase_ : List[Any] = '''{val_avg_rouge2:.4f}-{step_count}''' elif metric == "bleu": UpperCAmelCase_ : str = '''{val_avg_bleu:.4f}-{step_count}''' elif metric == "em": UpperCAmelCase_ : Optional[Any] = '''{val_avg_em:.4f}-{step_count}''' elif metric == "loss": UpperCAmelCase_ : Union[str, Any] = '''{val_avg_loss:.4f}-{step_count}''' else: raise NotImplementedError( F'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' ''' function.''' ) UpperCAmelCase_ : Optional[int] = ModelCheckpoint( dirpath=__lowercase , filename=__lowercase , monitor=F'''val_{metric}''' , mode='''max''' , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def snake_case_ ( __lowercase , __lowercase ): return EarlyStopping( monitor=F'''val_{metric}''' , mode='''min''' if '''loss''' in metric else '''max''' , patience=__lowercase , verbose=__lowercase , ) class lowerCAmelCase__( pl.Callback ): '''simple docstring''' def _lowerCamelCase ( self : Dict , __snake_case : Optional[int] , __snake_case : int ): '''simple docstring''' UpperCAmelCase_ : int = {f'''lr_group_{i}''': param['''lr'''] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__snake_case ) @rank_zero_only def _lowerCamelCase ( self : Tuple , __snake_case : pl.Trainer , __snake_case : pl.LightningModule , __snake_case : str , __snake_case : Optional[Any]=True ): '''simple docstring''' logger.info(f'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) UpperCAmelCase_ : int = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['''log''', '''progress_bar''', '''preds''']} ) # Log results UpperCAmelCase_ : int = Path(pl_module.hparams.output_dir ) if type_path == "test": UpperCAmelCase_ : Optional[Any] = od / '''test_results.txt''' UpperCAmelCase_ : Any = od / '''test_generations.txt''' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. UpperCAmelCase_ : Tuple = od / f'''{type_path}_results/{trainer.global_step:05d}.txt''' UpperCAmelCase_ : Tuple = od / f'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=__snake_case ) generations_file.parent.mkdir(exist_ok=__snake_case ) with open(__snake_case , '''a+''' ) as writer: for key in sorted(__snake_case ): if key in ["log", "progress_bar", "preds"]: continue UpperCAmelCase_ : str = metrics[key] if isinstance(__snake_case , torch.Tensor ): UpperCAmelCase_ : Dict = val.item() UpperCAmelCase_ : Optional[int] = f'''{key}: {val:.6f}\n''' writer.write(__snake_case ) if not save_generations: return if "preds" in metrics: UpperCAmelCase_ : Union[str, Any] = '''\n'''.join(metrics['''preds'''] ) generations_file.open('''w+''' ).write(__snake_case ) @rank_zero_only def _lowerCamelCase ( self : Any , __snake_case : Tuple , __snake_case : List[str] ): '''simple docstring''' try: UpperCAmelCase_ : List[str] = pl_module.model.model.num_parameters() except AttributeError: UpperCAmelCase_ : Union[str, Any] = pl_module.model.num_parameters() UpperCAmelCase_ : Tuple = count_trainable_parameters(__snake_case ) # mp stands for million parameters trainer.logger.log_metrics({'''n_params''': npars, '''mp''': npars / 1E6, '''grad_mp''': n_trainable_pars / 1E6} ) @rank_zero_only def _lowerCamelCase ( self : List[str] , __snake_case : pl.Trainer , __snake_case : pl.LightningModule ): '''simple docstring''' save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__snake_case , __snake_case , '''test''' ) @rank_zero_only def _lowerCamelCase ( self : Any , __snake_case : pl.Trainer , __snake_case : Optional[int] ): '''simple docstring''' save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
641
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed __UpperCamelCase : str = 'true' def snake_case_ ( __lowercase , __lowercase=8_2 , __lowercase=1_6 ): set_seed(4_2 ) UpperCAmelCase_ : Optional[int] = RegressionModel() UpperCAmelCase_ : Optional[int] = deepcopy(__lowercase ) UpperCAmelCase_ : Union[str, Any] = RegressionDataset(length=__lowercase ) UpperCAmelCase_ : Any = DataLoader(__lowercase , batch_size=__lowercase ) model.to(accelerator.device ) UpperCAmelCase_ , UpperCAmelCase_ : Dict = accelerator.prepare(__lowercase , __lowercase ) return model, ddp_model, dataloader def snake_case_ ( __lowercase , __lowercase=False ): UpperCAmelCase_ : Optional[int] = AutoTokenizer.from_pretrained('''hf-internal-testing/mrpc-bert-base-cased''' ) UpperCAmelCase_ : List[Any] = load_dataset('''glue''' , '''mrpc''' , split='''validation''' ) def tokenize_function(__lowercase ): UpperCAmelCase_ : int = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__lowercase , max_length=__lowercase ) return outputs with accelerator.main_process_first(): UpperCAmelCase_ : List[str] = dataset.map( __lowercase , batched=__lowercase , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) UpperCAmelCase_ : Any = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(__lowercase ): if use_longest: return tokenizer.pad(__lowercase , padding='''longest''' , return_tensors='''pt''' ) return tokenizer.pad(__lowercase , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' ) return DataLoader(__lowercase , shuffle=__lowercase , collate_fn=__lowercase , batch_size=1_6 ) def snake_case_ ( __lowercase , __lowercase ): UpperCAmelCase_ : Optional[int] = Accelerator(dispatch_batches=__lowercase , split_batches=__lowercase ) UpperCAmelCase_ : int = get_dataloader(__lowercase , not dispatch_batches ) UpperCAmelCase_ : Optional[int] = AutoModelForSequenceClassification.from_pretrained( '''hf-internal-testing/mrpc-bert-base-cased''' , return_dict=__lowercase ) UpperCAmelCase_ , UpperCAmelCase_ : Any = accelerator.prepare(__lowercase , __lowercase ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def snake_case_ ( __lowercase , __lowercase , __lowercase ): UpperCAmelCase_ : Dict = [] for batch in dataloader: UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = batch.values() with torch.no_grad(): UpperCAmelCase_ : List[Any] = model(__lowercase ) UpperCAmelCase_ , UpperCAmelCase_ : Dict = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) UpperCAmelCase_ , UpperCAmelCase_ : Any = [], [] for logit, targ in logits_and_targets: logits.append(__lowercase ) targs.append(__lowercase ) UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = torch.cat(__lowercase ), torch.cat(__lowercase ) return logits, targs def snake_case_ ( __lowercase , __lowercase=8_2 , __lowercase=False , __lowercase=False , __lowercase=1_6 ): UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Any = get_basic_setup(__lowercase , __lowercase , __lowercase ) UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = generate_predictions(__lowercase , __lowercase , __lowercase ) assert ( len(__lowercase ) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(__lowercase )}''' def snake_case_ ( __lowercase = False , __lowercase = False ): UpperCAmelCase_ : Optional[Any] = evaluate.load('''glue''' , '''mrpc''' ) UpperCAmelCase_ , UpperCAmelCase_ : Tuple = get_mrpc_setup(__lowercase , __lowercase ) # First do baseline UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = setup['''no'''] model.to(__lowercase ) model.eval() for batch in dataloader: batch.to(__lowercase ) with torch.inference_mode(): UpperCAmelCase_ : str = model(**__lowercase ) UpperCAmelCase_ : Dict = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=__lowercase , references=batch['''labels'''] ) UpperCAmelCase_ : Optional[int] = metric.compute() # Then do distributed UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = setup['''ddp'''] model.eval() for batch in dataloader: with torch.inference_mode(): UpperCAmelCase_ : Optional[int] = model(**__lowercase ) UpperCAmelCase_ : int = outputs.logits.argmax(dim=-1 ) UpperCAmelCase_ : Optional[int] = batch['''labels'''] UpperCAmelCase_ , UpperCAmelCase_ : Tuple = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=__lowercase , references=__lowercase ) UpperCAmelCase_ : Dict = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key] ), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def snake_case_ ( ): UpperCAmelCase_ : str = Accelerator(split_batches=__lowercase , dispatch_batches=__lowercase ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('''**Testing gather_for_metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''' ) test_mrpc(__lowercase , __lowercase ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test torch metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: UpperCAmelCase_ : Optional[Any] = Accelerator(split_batches=__lowercase , dispatch_batches=__lowercase ) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''' ) test_torch_metrics(__lowercase , 9_9 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test last batch is not dropped when perfectly divisible**''' ) UpperCAmelCase_ : List[Any] = Accelerator() test_torch_metrics(__lowercase , 5_1_2 ) accelerator.state._reset_state() def snake_case_ ( __lowercase ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
641
1
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean A_ = 0 A_ = [ [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], ] A_ = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right A_ = tuple[int, int] class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> None: '''simple docstring''' lowerCamelCase_ = pos_x lowerCamelCase_ = pos_y lowerCamelCase_ = (pos_y, pos_x) lowerCamelCase_ = goal_x lowerCamelCase_ = goal_y lowerCamelCase_ = g_cost lowerCamelCase_ = parent lowerCamelCase_ = self.calculate_heuristic() lowerCamelCase_ = self.g_cost + self.h_cost def UpperCamelCase( self ) -> float: '''simple docstring''' lowerCamelCase_ = self.pos_x - self.goal_x lowerCamelCase_ = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(SCREAMING_SNAKE_CASE_ ) + abs(SCREAMING_SNAKE_CASE_ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self , SCREAMING_SNAKE_CASE_ ) -> bool: '''simple docstring''' return self.f_cost < other.f_cost class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' lowerCamelCase_ = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = [self.start] lowerCamelCase_ = [] lowerCamelCase_ = False def UpperCamelCase( self ) -> list[TPosition]: '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() lowerCamelCase_ = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(SCREAMING_SNAKE_CASE_ ) self.closed_nodes.append(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.get_successors(SCREAMING_SNAKE_CASE_ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(SCREAMING_SNAKE_CASE_ ) else: # retrieve the best current path lowerCamelCase_ = self.open_nodes.pop(self.open_nodes.index(SCREAMING_SNAKE_CASE_ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(SCREAMING_SNAKE_CASE_ ) else: self.open_nodes.append(SCREAMING_SNAKE_CASE_ ) return [self.start.pos] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> list[Node]: '''simple docstring''' lowerCamelCase_ = [] for action in delta: lowerCamelCase_ = parent.pos_x + action[1] lowerCamelCase_ = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE_ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , SCREAMING_SNAKE_CASE_ , ) ) return successors def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> list[TPosition]: '''simple docstring''' lowerCamelCase_ = node lowerCamelCase_ = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) lowerCamelCase_ = current_node.parent path.reverse() return path class UpperCAmelCase : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None: '''simple docstring''' lowerCamelCase_ = AStar(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = AStar(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = False def UpperCamelCase( self ) -> list[TPosition]: '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() lowerCamelCase_ = self.fwd_astar.open_nodes.pop(0 ) lowerCamelCase_ = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.fwd_astar.closed_nodes.append(SCREAMING_SNAKE_CASE_ ) self.bwd_astar.closed_nodes.append(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = current_bwd_node lowerCamelCase_ = current_fwd_node lowerCamelCase_ = { self.fwd_astar: self.fwd_astar.get_successors(SCREAMING_SNAKE_CASE_ ), self.bwd_astar: self.bwd_astar.get_successors(SCREAMING_SNAKE_CASE_ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(SCREAMING_SNAKE_CASE_ ) else: # retrieve the best current path lowerCamelCase_ = astar.open_nodes.pop( astar.open_nodes.index(SCREAMING_SNAKE_CASE_ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(SCREAMING_SNAKE_CASE_ ) else: astar.open_nodes.append(SCREAMING_SNAKE_CASE_ ) return [self.fwd_astar.start.pos] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> list[TPosition]: '''simple docstring''' lowerCamelCase_ = self.fwd_astar.retrace_path(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = self.bwd_astar.retrace_path(SCREAMING_SNAKE_CASE_ ) bwd_path.pop() bwd_path.reverse() lowerCamelCase_ = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] A_ = (0, 0) A_ = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) A_ = time.time() A_ = AStar(init, goal) A_ = a_star.search() A_ = time.time() - start_time print(f'''AStar execution time = {end_time:f} seconds''') A_ = time.time() A_ = BidirectionalAStar(init, goal) A_ = time.time() - bd_start_time print(f'''BidirectionalAStar execution time = {bd_end_time:f} seconds''')
42
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. UpperCAmelCase__ : Union[str, Any] = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def lowercase_ ( _snake_case ): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_snake_case ) def lowercase_ ( _snake_case ): from diffusers.utils.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE__ : Any = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(_snake_case ,id=_snake_case )
223
0
'''simple docstring''' def __lowerCamelCase ( _lowercase = "The quick brown fox jumps over the lazy dog" , ) -> bool: UpperCAmelCase : Union[str, Any] = set() # Replace all the whitespace in our sentence UpperCAmelCase : List[str] = input_str.replace(""" """ , """""" ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(_lowercase ) == 2_6 def __lowerCamelCase ( _lowercase = "The quick brown fox jumps over the lazy dog" , ) -> bool: UpperCAmelCase : Tuple = [False] * 2_6 for char in input_str: if char.islower(): UpperCAmelCase : Any = True elif char.isupper(): UpperCAmelCase : Union[str, Any] = True return all(_lowercase ) def __lowerCamelCase ( _lowercase = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 2_6 def __lowerCamelCase ( ) -> None: from timeit import timeit UpperCAmelCase : str = """from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest""" print(timeit("""is_pangram()""" , setup=_lowercase ) ) print(timeit("""is_pangram_faster()""" , setup=_lowercase ) ) print(timeit("""is_pangram_fastest()""" , setup=_lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
672
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib a : Any = get_logger() a : Optional[dict] = None class UpperCamelCase_ ( TensorFormatter[Mapping, 'jax.Array', Mapping] ): def __init__( self , A=None , A=None , **A ) -> str: super().__init__(features=A ) import jax from jaxlib.xla_client import Device if isinstance(A , A ): raise ValueError( f'''Expected {device} to be a `str` not {type(A )}, as `jaxlib.xla_extension.Device` ''' """is not serializable neither with `pickle` nor with `dill`. Instead you can surround """ """the device with `str()` to get its string identifier that will be internally mapped """ """to the actual `jaxlib.xla_extension.Device`.""" ) UpperCAmelCase : Optional[int] = device if isinstance(A , A ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: UpperCAmelCase : Any = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( f'''Device with string identifier {self.device} not listed among the available ''' f'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ''' f'''device: {str(jax.devices()[0] )}.''' ) UpperCAmelCase : List[Any] = str(jax.devices()[0] ) UpperCAmelCase : Union[str, Any] = jnp_array_kwargs @staticmethod def _lowercase( ) -> Dict[str, "jaxlib.xla_extension.Device"]: import jax return {str(A ): device for device in jax.devices()} def _lowercase( self , A ) -> str: import jax import jax.numpy as jnp if isinstance(A , A ) and column: if all( isinstance(A , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(A , axis=0 ) return column def _lowercase( self , A ) -> Tuple: import jax import jax.numpy as jnp if isinstance(A , (str, bytes, type(A )) ): return value elif isinstance(A , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() UpperCAmelCase : List[str] = {} if isinstance(A , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: UpperCAmelCase : str = {"""dtype""": jnp.intaa} else: UpperCAmelCase : int = {"""dtype""": jnp.intaa} elif isinstance(A , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): UpperCAmelCase : Any = {"""dtype""": jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(A , PIL.Image.Image ): UpperCAmelCase : List[str] = np.asarray(A ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: UpperCAmelCase : Dict = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(A , **{**default_dtype, **self.jnp_array_kwargs} ) def _lowercase( self , A ) -> Tuple: import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(A , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(A , """__array__""" ) and not isinstance(A , jax.Array ): UpperCAmelCase : Optional[int] = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(A , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(A ) for substruct in data_struct] ) elif isinstance(A , (list, tuple) ): return self._consolidate([self.recursive_tensorize(A ) for substruct in data_struct] ) return self._tensorize(A ) def _lowercase( self , A ) -> Dict: return map_nested(self._recursive_tensorize , A , map_list=A ) def _lowercase( self , A ) -> Mapping: UpperCAmelCase : Union[str, Any] = self.numpy_arrow_extractor().extract_row(A ) UpperCAmelCase : Dict = self.python_features_decoder.decode_row(A ) return self.recursive_tensorize(A ) def _lowercase( self , A ) -> "jax.Array": UpperCAmelCase : int = self.numpy_arrow_extractor().extract_column(A ) UpperCAmelCase : Optional[Any] = self.python_features_decoder.decode_column(A , pa_table.column_names[0] ) UpperCAmelCase : Optional[int] = self.recursive_tensorize(A ) UpperCAmelCase : Any = self._consolidate(A ) return column def _lowercase( self , A ) -> Mapping: UpperCAmelCase : Optional[int] = self.numpy_arrow_extractor().extract_batch(A ) UpperCAmelCase : List[str] = self.python_features_decoder.decode_batch(A ) UpperCAmelCase : Union[str, Any] = self.recursive_tensorize(A ) for column_name in batch: UpperCAmelCase : Optional[Any] = self._consolidate(batch[column_name] ) return batch
672
1
from decimal import Decimal, getcontext from math import ceil, factorial def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ): if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("Undefined for non-integers" ) elif precision < 1: raise ValueError("Undefined for non-natural numbers" ) snake_case_ : List[str] = precision snake_case_ : Union[str, Any] = ceil(precision / 1_4 ) snake_case_ : List[str] = 4_2_6_8_8_0 * Decimal(1_0_0_0_5 ).sqrt() snake_case_ : str = 1 snake_case_ : List[str] = 1_3_5_9_1_4_0_9 snake_case_ : str = Decimal(lowerCAmelCase_ ) for k in range(1 , lowerCAmelCase_ ): snake_case_ : Tuple = factorial(6 * k ) // (factorial(3 * k ) * factorial(lowerCAmelCase_ ) ** 3) linear_term += 5_4_5_1_4_0_1_3_4 exponential_term *= -2_6_2_5_3_7_4_1_2_6_4_0_7_6_8_0_0_0 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": UpperCAmelCase = 5_0 print(F"The first {n} digits of pi is: {pi(n)}")
666
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json", } class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Dict = "git_vision_model" def __init__( self : int , A__ : Union[str, Any]=7_68 , A__ : List[Any]=30_72 , A__ : Tuple=12 , A__ : Optional[Any]=12 , A__ : Optional[int]=3 , A__ : List[str]=2_24 , A__ : Dict=16 , A__ : int="quick_gelu" , A__ : Any=1E-5 , A__ : Tuple=0.0 , A__ : Optional[int]=0.02 , **A__ : List[str] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) snake_case_ : Optional[Any] = hidden_size snake_case_ : str = intermediate_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : int = num_attention_heads snake_case_ : Optional[int] = num_channels snake_case_ : Union[str, Any] = patch_size snake_case_ : List[str] = image_size snake_case_ : List[Any] = initializer_range snake_case_ : Any = attention_dropout snake_case_ : Any = layer_norm_eps snake_case_ : int = hidden_act @classmethod def UpperCAmelCase__ ( cls : List[Any] , A__ : Union[str, os.PathLike] , **A__ : Optional[int] ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(A__ ) snake_case_ ,snake_case_ : Tuple = cls.get_config_dict(A__ , **A__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("model_type" ) == "git": snake_case_ : Any = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(A__ , **A__ ) class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = "git" def __init__( self : Any , A__ : List[str]=None , A__ : List[str]=3_05_22 , A__ : Tuple=7_68 , A__ : Tuple=6 , A__ : str=12 , A__ : Any=30_72 , A__ : List[str]="gelu" , A__ : int=0.1 , A__ : Dict=0.1 , A__ : Any=10_24 , A__ : Optional[Any]=0.02 , A__ : Optional[Any]=1E-12 , A__ : Dict=0 , A__ : Any="absolute" , A__ : Tuple=True , A__ : Any=False , A__ : Tuple=1_01 , A__ : Tuple=1_02 , A__ : List[Any]=None , **A__ : List[str] , ) -> int: '''simple docstring''' super().__init__(bos_token_id=A__ , eos_token_id=A__ , pad_token_id=A__ , **A__ ) if vision_config is None: snake_case_ : int = {} logger.info("vision_config is None. initializing the GitVisionConfig with default values." ) snake_case_ : str = GitVisionConfig(**A__ ) snake_case_ : int = vocab_size snake_case_ : List[Any] = hidden_size snake_case_ : Tuple = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : Any = hidden_act snake_case_ : Dict = intermediate_size snake_case_ : Any = hidden_dropout_prob snake_case_ : Any = attention_probs_dropout_prob snake_case_ : Union[str, Any] = max_position_embeddings snake_case_ : List[str] = initializer_range snake_case_ : List[str] = layer_norm_eps snake_case_ : Any = position_embedding_type snake_case_ : Union[str, Any] = use_cache snake_case_ : str = tie_word_embeddings snake_case_ : List[Any] = num_image_with_embedding snake_case_ : Dict = bos_token_id snake_case_ : int = eos_token_id def UpperCAmelCase__ ( self : Any ) -> int: '''simple docstring''' snake_case_ : Tuple = copy.deepcopy(self.__dict__ ) snake_case_ : Optional[int] = self.vision_config.to_dict() snake_case_ : Tuple = self.__class__.model_type return output
666
1
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand _lowerCAmelCase = ( """4S 3H 2C 7S 5H""", """9D 8H 2C 6S 7H""", """2D 6D 9D TH 7D""", """TC 8C 2S JH 6C""", """JH 8S TH AH QH""", """TS KS 5S 9S AC""", """KD 6S 9D TH AD""", """KS 8D 4D 9S 4S""", # pair """8C 4S KH JS 4D""", # pair """QH 8H KD JH 8S""", # pair """KC 4H KS 2H 8D""", # pair """KD 4S KC 3H 8S""", # pair """AH 8S AS KC JH""", # pair """3H 4C 4H 3S 2H""", # 2 pairs """5S 5D 2C KH KH""", # 2 pairs """3C KH 5D 5S KH""", # 2 pairs """AS 3C KH AD KH""", # 2 pairs """7C 7S 3S 7H 5S""", # 3 of a kind """7C 7S KH 2H 7H""", # 3 of a kind """AC KH QH AH AS""", # 3 of a kind """2H 4D 3C AS 5S""", # straight (low ace) """3C 5C 4C 2C 6H""", # straight """6S 8S 7S 5H 9H""", # straight """JS QS 9H TS KH""", # straight """QC KH TS JS AH""", # straight (high ace) """8C 9C 5C 3C TC""", # flush """3S 8S 9S 5S KS""", # flush """4C 5C 9C 8C KC""", # flush """JH 8H AH KH QH""", # flush """3D 2H 3H 2C 2D""", # full house """2H 2C 3S 3H 3D""", # full house """KH KC 3S 3H 3D""", # full house """JC 6H JS JD JH""", # 4 of a kind """JC 7H JS JD JH""", # 4 of a kind """JC KH JS JD JH""", # 4 of a kind """2S AS 4S 5S 3S""", # straight flush (low ace) """2D 6D 3D 4D 5D""", # straight flush """5C 6C 3C 7C 4C""", # straight flush """JH 9H TH KH QH""", # straight flush """JH AH TH KH QH""", # royal flush (high ace straight flush) ) _lowerCAmelCase = ( ("""2H 3H 4H 5H 6H""", """KS AS TS QS JS""", """Loss"""), ("""2H 3H 4H 5H 6H""", """AS AD AC AH JD""", """Win"""), ("""AS AH 2H AD AC""", """JS JD JC JH 3D""", """Win"""), ("""2S AH 2H AS AC""", """JS JD JC JH AD""", """Loss"""), ("""2S AH 2H AS AC""", """2H 3H 5H 6H 7H""", """Win"""), ("""AS 3S 4S 8S 2S""", """2H 3H 5H 6H 7H""", """Win"""), ("""2H 3H 5H 6H 7H""", """2S 3H 4H 5S 6C""", """Win"""), ("""2S 3H 4H 5S 6C""", """3D 4C 5H 6H 2S""", """Tie"""), ("""2S 3H 4H 5S 6C""", """AH AC 5H 6H AS""", """Win"""), ("""2S 2H 4H 5S 4C""", """AH AC 5H 6H AS""", """Loss"""), ("""2S 2H 4H 5S 4C""", """AH AC 5H 6H 7S""", """Win"""), ("""6S AD 7H 4S AS""", """AH AC 5H 6H 7S""", """Loss"""), ("""2S AH 4H 5S KC""", """AH AC 5H 6H 7S""", """Loss"""), ("""2S 3H 6H 7S 9C""", """7H 3C TH 6H 9S""", """Loss"""), ("""4S 5H 6H TS AC""", """3S 5H 6H TS AC""", """Win"""), ("""2S AH 4H 5S 6C""", """AD 4C 5H 6H 2C""", """Tie"""), ("""AS AH 3H AD AC""", """AS AH 2H AD AC""", """Win"""), ("""AH AC 5H 5C QS""", """AH AC 5H 5C KS""", """Loss"""), ("""AH AC 5H 5C QS""", """KH KC 5H 5C QS""", """Win"""), ("""7C 7S KH 2H 7H""", """3C 3S AH 2H 3H""", """Win"""), ("""3C 3S AH 2H 3H""", """7C 7S KH 2H 7H""", """Loss"""), ("""6H 5H 4H 3H 2H""", """5H 4H 3H 2H AH""", """Win"""), ("""5H 4H 3H 2H AH""", """5H 4H 3H 2H AH""", """Tie"""), ("""5H 4H 3H 2H AH""", """6H 5H 4H 3H 2H""", """Loss"""), ("""AH AD KS KC AC""", """AH KD KH AC KC""", """Win"""), ("""2H 4D 3C AS 5S""", """2H 4D 3C 6S 5S""", """Loss"""), ("""2H 3S 3C 3H 2S""", """3S 3C 2S 2H 2D""", """Win"""), ("""4D 6D 5D 2D JH""", """3S 8S 3H TC KH""", """Loss"""), ("""4S 6C 8S 3S 7S""", """AD KS 2D 7D 7C""", """Loss"""), ("""6S 4C 7H 8C 3H""", """5H JC AH 9D 9C""", """Loss"""), ("""9D 9H JH TC QH""", """3C 2S JS 5C 7H""", """Win"""), ("""2H TC 8S AD 9S""", """4H TS 7H 2C 5C""", """Win"""), ("""9D 3S 2C 7S 7C""", """JC TD 3C TC 9H""", """Loss"""), ) _lowerCAmelCase = ( ("""2H 3H 4H 5H 6H""", True), ("""AS AH 2H AD AC""", False), ("""2H 3H 5H 6H 7H""", True), ("""KS AS TS QS JS""", True), ("""8H 9H QS JS TH""", False), ("""AS 3S 4S 8S 2S""", True), ) _lowerCAmelCase = ( ("""2H 3H 4H 5H 6H""", True), ("""AS AH 2H AD AC""", False), ("""2H 3H 5H 6H 7H""", False), ("""KS AS TS QS JS""", True), ("""8H 9H QS JS TH""", True), ) _lowerCAmelCase = ( ("""2H 4D 3C AS 5S""", True, [5, 4, 3, 2, 14]), ("""2H 5D 3C AS 5S""", False, [14, 5, 5, 3, 2]), ("""JH QD KC AS TS""", False, [14, 13, 12, 11, 10]), ("""9D 3S 2C 7S 7C""", False, [9, 7, 7, 3, 2]), ) _lowerCAmelCase = ( ("""JH AH TH KH QH""", 0), ("""JH 9H TH KH QH""", 0), ("""JC KH JS JD JH""", 7), ("""KH KC 3S 3H 3D""", 6), ("""8C 9C 5C 3C TC""", 0), ("""JS QS 9H TS KH""", 0), ("""7C 7S KH 2H 7H""", 3), ("""3C KH 5D 5S KH""", 2), ("""QH 8H KD JH 8S""", 1), ("""2D 6D 9D TH 7D""", 0), ) _lowerCAmelCase = ( ("""JH AH TH KH QH""", 23), ("""JH 9H TH KH QH""", 22), ("""JC KH JS JD JH""", 21), ("""KH KC 3S 3H 3D""", 20), ("""8C 9C 5C 3C TC""", 19), ("""JS QS 9H TS KH""", 18), ("""7C 7S KH 2H 7H""", 17), ("""3C KH 5D 5S KH""", 16), ("""QH 8H KD JH 8S""", 15), ("""2D 6D 9D TH 7D""", 14), ) def _lowerCAmelCase ( ): '''simple docstring''' A_ , A_ : Optional[Any] = randrange(len(_lowerCAmelCase ) ), randrange(len(_lowerCAmelCase ) ) A_ : int = ["""Loss""", """Tie""", """Win"""][(play >= oppo) + (play > oppo)] A_ , A_ : Optional[int] = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def _lowerCAmelCase ( _lowerCAmelCase = 1_0_0 ): '''simple docstring''' return (generate_random_hand() for _ in range(_lowerCAmelCase )) @pytest.mark.parametrize("""hand, expected""" ,_lowerCAmelCase ) def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' assert PokerHand(_lowerCAmelCase )._is_flush() == expected @pytest.mark.parametrize("""hand, expected""" ,_lowerCAmelCase ) def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' assert PokerHand(_lowerCAmelCase )._is_straight() == expected @pytest.mark.parametrize("""hand, expected, card_values""" ,_lowerCAmelCase ) def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' A_ : List[str] = PokerHand(_lowerCAmelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("""hand, expected""" ,_lowerCAmelCase ) def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' assert PokerHand(_lowerCAmelCase )._is_same_kind() == expected @pytest.mark.parametrize("""hand, expected""" ,_lowerCAmelCase ) def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' assert PokerHand(_lowerCAmelCase )._hand_type == expected @pytest.mark.parametrize("""hand, other, expected""" ,_lowerCAmelCase ) def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' assert PokerHand(_lowerCAmelCase ).compare_with(PokerHand(_lowerCAmelCase ) ) == expected @pytest.mark.parametrize("""hand, other, expected""" ,generate_random_hands() ) def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' assert PokerHand(_lowerCAmelCase ).compare_with(PokerHand(_lowerCAmelCase ) ) == expected def _lowerCAmelCase ( ): '''simple docstring''' A_ : Optional[Any] = [PokerHand(_lowerCAmelCase ) for hand in SORTED_HANDS] A_ : Tuple = poker_hands.copy() shuffle(_lowerCAmelCase ) A_ : Dict = chain(sorted(_lowerCAmelCase ) ) for index, hand in enumerate(_lowerCAmelCase ): assert hand == poker_hands[index] def _lowerCAmelCase ( ): '''simple docstring''' A_ : Any = [PokerHand("""2D AC 3H 4H 5S""" ), PokerHand("""2S 3H 4H 5S 6C""" )] pokerhands.sort(reverse=_lowerCAmelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def _lowerCAmelCase ( ): '''simple docstring''' A_ : List[Any] = PokerHand("""2C 4S AS 3D 5C""" ) A_ : Tuple = True A_ : Any = [5, 4, 3, 2, 1_4] for _ in range(1_0 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def _lowerCAmelCase ( ): '''simple docstring''' A_ : Tuple = 0 A_ : Union[str, Any] = os.path.abspath(os.path.dirname(_lowerCAmelCase ) ) A_ : Tuple = os.path.join(_lowerCAmelCase ,"""poker_hands.txt""" ) with open(_lowerCAmelCase ) as file_hand: for line in file_hand: A_ : Tuple = line[:1_4].strip() A_ : Dict = line[1_5:].strip() A_ , A_ : List[str] = PokerHand(_lowerCAmelCase ), PokerHand(_lowerCAmelCase ) A_ : str = player.compare_with(_lowerCAmelCase ) if output == "Win": answer += 1 assert answer == 3_7_6
481
import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig 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_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 ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _UpperCAmelCase : def __init__( self , a__ , a__=13 , a__=30 , a__=2 , a__=3 , a__=True , a__=True , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=10 , a__=0.02 , a__=3 , a__=0.6 , a__=None , ): A_ : int = parent A_ : Optional[int] = batch_size A_ : Any = image_size A_ : Optional[int] = patch_size A_ : int = num_channels A_ : str = is_training A_ : str = use_labels A_ : str = hidden_size A_ : Union[str, Any] = num_hidden_layers A_ : Tuple = num_attention_heads A_ : Any = intermediate_size A_ : List[Any] = hidden_act A_ : List[Any] = hidden_dropout_prob A_ : Optional[int] = attention_probs_dropout_prob A_ : str = type_sequence_label_size A_ : int = initializer_range A_ : List[Any] = mask_ratio A_ : str = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) A_ : Optional[Any] = (image_size // patch_size) ** 2 A_ : List[Any] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def _lowerCamelCase ( self ): A_ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A_ : int = None if self.use_labels: A_ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A_ : Any = self.get_config() return config, pixel_values, labels def _lowerCamelCase ( self ): return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def _lowerCamelCase ( self , a__ , a__ , a__ ): A_ : Optional[int] = ViTMAEModel(config=a__ ) model.to(a__ ) model.eval() A_ : int = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCamelCase ( self , a__ , a__ , a__ ): A_ : int = ViTMAEForPreTraining(a__ ) model.to(a__ ) model.eval() A_ : Optional[Any] = model(a__ ) A_ : Dict = (self.image_size // self.patch_size) ** 2 A_ : Optional[int] = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images A_ : Optional[int] = 1 A_ : Any = ViTMAEForPreTraining(a__ ) model.to(a__ ) model.eval() A_ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A_ : List[Any] = model(a__ ) A_ : Optional[int] = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def _lowerCamelCase ( self ): A_ : Optional[Any] = self.prepare_config_and_inputs() A_ , A_ , A_ : Any = config_and_inputs A_ : Dict = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase ): a = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () a = {'''feature-extraction''': ViTMAEModel} if is_torch_available() else {} a = False a = False a = False a = False def _lowerCamelCase ( self ): A_ : int = ViTMAEModelTester(self ) A_ : List[Any] = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def _lowerCamelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def _lowerCamelCase ( self ): pass def _lowerCamelCase ( self ): A_ , A_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : Dict = model_class(a__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) A_ : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a__ , nn.Linear ) ) def _lowerCamelCase ( self ): A_ , A_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : Any = model_class(a__ ) A_ : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A_ : Dict = [*signature.parameters.keys()] A_ : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , a__ ) def _lowerCamelCase ( self ): A_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def _lowerCamelCase ( self ): A_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*a__ ) def _lowerCamelCase ( self , a__ , a__ , a__ ): # make masks reproducible np.random.seed(2 ) A_ : Optional[Any] = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) A_ : List[str] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) A_ : Optional[Any] = torch.from_numpy(a__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument A_ : Any = pt_noise super().check_pt_tf_models(a__ , a__ , a__ ) def _lowerCamelCase ( self ): A_ , A_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : List[Any] = model_class(a__ ) model.to(a__ ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): A_ : Union[str, Any] = model(**self._prepare_for_class(a__ , a__ ) ) A_ : int = outputs[0].cpu().numpy() A_ : Union[str, Any] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a__ ) A_ : Union[str, Any] = model_class.from_pretrained(a__ ) model.to(a__ ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): A_ : Optional[int] = model(**self._prepare_for_class(a__ , a__ ) ) # Make sure we don't have nans A_ : Optional[int] = after_outputs[0].cpu().numpy() A_ : str = 0 A_ : Optional[int] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a__ , 1E-5 ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def _lowerCamelCase ( self ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def _lowerCamelCase ( self ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def _lowerCamelCase ( self ): pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def _lowerCamelCase ( self ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _lowerCamelCase ( self ): pass @slow def _lowerCamelCase ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A_ : Union[str, Any] = ViTMAEModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def _lowerCAmelCase ( ): '''simple docstring''' A_ : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _UpperCAmelCase ( unittest.TestCase ): @cached_property def _lowerCamelCase ( self ): return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def _lowerCamelCase ( self ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) A_ : Union[str, Any] = ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ).to(a__ ) A_ : Optional[Any] = self.default_image_processor A_ : Union[str, Any] = prepare_img() A_ : Union[str, Any] = image_processor(images=a__ , return_tensors="""pt""" ).to(a__ ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) A_ : Optional[int] = ViTMAEConfig() A_ : Tuple = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) A_ : Tuple = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): A_ : Dict = model(**a__ , noise=torch.from_numpy(a__ ).to(device=a__ ) ) # verify the logits A_ : Tuple = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , a__ ) A_ : List[str] = torch.tensor( [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(a__ ) , atol=1E-4 ) )
481
1
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging __UpperCamelCase : List[str] = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = { '''bigscience/bloom''': '''https://huggingface.co/bigscience/bloom/resolve/main/config.json''', '''bigscience/bloom-560m''': '''https://huggingface.co/bigscience/bloom-560m/blob/main/config.json''', '''bigscience/bloom-1b1''': '''https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json''', '''bigscience/bloom-1b7''': '''https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json''', '''bigscience/bloom-3b''': '''https://huggingface.co/bigscience/bloom-3b/blob/main/config.json''', '''bigscience/bloom-7b1''': '''https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json''', } class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = "bloom" lowercase__ = ["past_key_values"] lowercase__ = { "num_hidden_layers": "n_layer", "num_attention_heads": "n_head", } def __init__( self : int ,lowercase_ : Dict=2_5_0_8_8_0 ,lowercase_ : Dict=6_4 ,lowercase_ : Dict=2 ,lowercase_ : Union[str, Any]=8 ,lowercase_ : Tuple=1E-5 ,lowercase_ : str=0.02 ,lowercase_ : List[str]=True ,lowercase_ : Optional[Any]=1 ,lowercase_ : int=2 ,lowercase_ : List[str]=False ,lowercase_ : List[str]=0.0 ,lowercase_ : int=0.0 ,lowercase_ : Dict=1 ,lowercase_ : Optional[int]=False ,**lowercase_ : List[Any] ,): lowerCAmelCase__ : Union[str, Any] = vocab_size # Backward compatibility with n_embed kwarg lowerCAmelCase__ : Optional[int] = kwargs.pop('''n_embed''' ,lowercase_ ) lowerCAmelCase__ : Union[str, Any] = hidden_size if n_embed is None else n_embed lowerCAmelCase__ : List[str] = n_layer lowerCAmelCase__ : Any = n_head lowerCAmelCase__ : Union[str, Any] = layer_norm_epsilon lowerCAmelCase__ : Any = initializer_range lowerCAmelCase__ : Union[str, Any] = use_cache lowerCAmelCase__ : Union[str, Any] = pretraining_tp lowerCAmelCase__ : Optional[Any] = apply_residual_connection_post_layernorm lowerCAmelCase__ : Tuple = hidden_dropout lowerCAmelCase__ : Optional[int] = attention_dropout lowerCAmelCase__ : Tuple = bos_token_id lowerCAmelCase__ : Dict = eos_token_id lowerCAmelCase__ : Dict = slow_but_exact super().__init__(bos_token_id=lowercase_ ,eos_token_id=lowercase_ ,**lowercase_ ) class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = version.parse("1.12" ) def __init__( self : Optional[Any] ,lowercase_ : PretrainedConfig ,lowercase_ : str = "default" ,lowercase_ : List[PatchingSpec] = None ,lowercase_ : bool = False ,): super().__init__(lowercase_ ,task=lowercase_ ,patching_specs=lowercase_ ,use_past=lowercase_ ) if not getattr(self._config ,'''pad_token_id''' ,lowercase_ ): # TODO: how to do that better? lowerCAmelCase__ : Union[str, Any] = 0 @property def __lowerCAmelCase ( self : int ): lowerCAmelCase__ : Union[str, Any] = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(lowercase_ ,direction='''inputs''' ,inverted_values_shape=lowercase_ ) lowerCAmelCase__ : Dict = {0: '''batch''', 1: '''past_sequence + sequence'''} else: lowerCAmelCase__ : int = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def __lowerCAmelCase ( self : int ): return self._config.n_layer @property def __lowerCAmelCase ( self : Optional[int] ): return self._config.n_head @property def __lowerCAmelCase ( self : Union[str, Any] ): return 1E-3 def __lowerCAmelCase ( self : Any ,lowercase_ : "PreTrainedTokenizer" ,lowercase_ : int = -1 ,lowercase_ : int = -1 ,lowercase_ : bool = False ,lowercase_ : Optional["TensorType"] = None ,): lowerCAmelCase__ : Optional[int] = super(lowercase_ ,self ).generate_dummy_inputs( lowercase_ ,batch_size=lowercase_ ,seq_length=lowercase_ ,is_pair=lowercase_ ,framework=lowercase_ ) # We need to order the input in the way they appears in the forward() lowerCAmelCase__ : Dict = 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 lowerCAmelCase__ ,lowerCAmelCase__ : Union[str, Any] = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values lowerCAmelCase__ : List[str] = seqlen + 2 lowerCAmelCase__ : List[Any] = self._config.hidden_size // self.num_attention_heads lowerCAmelCase__ : int = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) lowerCAmelCase__ : Tuple = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) lowerCAmelCase__ : List[str] = [ (torch.zeros(lowercase_ ), torch.zeros(lowercase_ )) for _ in range(self.num_layers ) ] lowerCAmelCase__ : Optional[int] = common_inputs['''attention_mask'''] if self.use_past: lowerCAmelCase__ : List[str] = ordered_inputs['''attention_mask'''].dtype lowerCAmelCase__ : Dict = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(lowercase_ ,lowercase_ ,dtype=lowercase_ )] ,dim=1 ) return ordered_inputs @property def __lowerCAmelCase ( self : List[str] ): return 1_3
450
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def __init__( self : Any ,lowercase_ : Dict ,lowercase_ : List[str]=7 ,lowercase_ : Tuple=3 ,lowercase_ : List[str]=1_8 ,lowercase_ : Optional[Any]=3_0 ,lowercase_ : List[Any]=4_0_0 ,lowercase_ : List[Any]=True ,lowercase_ : Any=None ,lowercase_ : Optional[Any]=True ,lowercase_ : str=None ,lowercase_ : List[Any]=True ,lowercase_ : Dict=[0.5, 0.5, 0.5] ,lowercase_ : Dict=[0.5, 0.5, 0.5] ,): lowerCAmelCase__ : Any = size if size is not None else {'''shortest_edge''': 1_8} lowerCAmelCase__ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8} lowerCAmelCase__ : Dict = parent lowerCAmelCase__ : Dict = batch_size lowerCAmelCase__ : List[str] = num_channels lowerCAmelCase__ : Any = image_size lowerCAmelCase__ : Union[str, Any] = min_resolution lowerCAmelCase__ : Dict = max_resolution lowerCAmelCase__ : List[str] = do_resize lowerCAmelCase__ : Optional[Any] = size lowerCAmelCase__ : Tuple = do_center_crop lowerCAmelCase__ : Optional[int] = crop_size lowerCAmelCase__ : List[str] = do_normalize lowerCAmelCase__ : Tuple = image_mean lowerCAmelCase__ : int = image_std def __lowerCAmelCase ( self : List[str] ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class SCREAMING_SNAKE_CASE ( a_ , unittest.TestCase ): """simple docstring""" lowercase__ = LevitImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self : List[str] ): lowerCAmelCase__ : Optional[Any] = LevitImageProcessingTester(self ) @property def __lowerCAmelCase ( self : Any ): return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self : str ): lowerCAmelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase_ ,'''image_mean''' ) ) self.assertTrue(hasattr(lowercase_ ,'''image_std''' ) ) self.assertTrue(hasattr(lowercase_ ,'''do_normalize''' ) ) self.assertTrue(hasattr(lowercase_ ,'''do_resize''' ) ) self.assertTrue(hasattr(lowercase_ ,'''do_center_crop''' ) ) self.assertTrue(hasattr(lowercase_ ,'''size''' ) ) def __lowerCAmelCase ( self : Any ): lowerCAmelCase__ : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'''shortest_edge''': 1_8} ) self.assertEqual(image_processor.crop_size ,{'''height''': 1_8, '''width''': 1_8} ) lowerCAmelCase__ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ,size=4_2 ,crop_size=8_4 ) self.assertEqual(image_processor.size ,{'''shortest_edge''': 4_2} ) self.assertEqual(image_processor.crop_size ,{'''height''': 8_4, '''width''': 8_4} ) def __lowerCAmelCase ( self : Union[str, Any] ): pass def __lowerCAmelCase ( self : Optional[int] ): # Initialize image_processing lowerCAmelCase__ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=lowercase_ ) for image in image_inputs: self.assertIsInstance(lowercase_ ,Image.Image ) # Test not batched input lowerCAmelCase__ : Any = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) # Test batched lowerCAmelCase__ : Optional[int] = image_processing(lowercase_ ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) def __lowerCAmelCase ( self : Union[str, Any] ): # Initialize image_processing lowerCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ : Optional[Any] = prepare_image_inputs(self.image_processor_tester ,equal_resolution=lowercase_ ,numpify=lowercase_ ) for image in image_inputs: self.assertIsInstance(lowercase_ ,np.ndarray ) # Test not batched input lowerCAmelCase__ : Tuple = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) # Test batched lowerCAmelCase__ : Union[str, Any] = image_processing(lowercase_ ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) def __lowerCAmelCase ( self : int ): # Initialize image_processing lowerCAmelCase__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ : Dict = prepare_image_inputs(self.image_processor_tester ,equal_resolution=lowercase_ ,torchify=lowercase_ ) for image in image_inputs: self.assertIsInstance(lowercase_ ,torch.Tensor ) # Test not batched input lowerCAmelCase__ : Dict = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) # Test batched lowerCAmelCase__ : Optional[int] = image_processing(lowercase_ ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,)
450
1
"""simple docstring""" import os from datetime import datetime as dt from github import Github __lowercase : Optional[int] = [ """good first issue""", """good second issue""", """good difficult issue""", """enhancement""", """new pipeline/model""", """new scheduler""", """wip""", ] def lowerCamelCase_ ( ): lowerCamelCase_ = Github(os.environ['''GITHUB_TOKEN'''] ) lowerCamelCase_ = g.get_repo('''huggingface/diffusers''' ) lowerCamelCase_ = repo.get_issues(state='''open''' ) for issue in open_issues: lowerCamelCase_ = sorted(issue.get_comments() , key=lambda _lowerCamelCase : i.created_at , reverse=_lowerCamelCase ) lowerCamelCase_ = comments[0] if len(_lowerCamelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 3_0 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state='''closed''' ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state='''open''' ) issue.remove_from_labels('''stale''' ) elif ( (dt.utcnow() - issue.updated_at).days > 2_3 and (dt.utcnow() - issue.created_at).days >= 3_0 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( '''This issue has been automatically marked as stale because it has not had ''' '''recent activity. If you think this still needs to be addressed ''' '''please comment on this thread.\n\nPlease note that issues that do not follow the ''' '''[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) ''' '''are likely to be ignored.''' ) issue.add_to_labels('''stale''' ) if __name__ == "__main__": main()
66
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def lowerCamelCase_ ( _lowerCamelCase : int = 8 ): lowerCamelCase_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_lowerCamelCase ) for _ in range(_lowerCamelCase ) ) def lowerCamelCase_ ( _lowerCamelCase : str , _lowerCamelCase : int ): # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_lowerCamelCase ) lowerCamelCase_ = i // 3 lowerCamelCase_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) lowerCamelCase_ = ( chars_incl + random(_lowerCamelCase , quotient + remainder ) + random(_lowerCamelCase , _lowerCamelCase ) + random(_lowerCamelCase , _lowerCamelCase ) ) lowerCamelCase_ = list(_lowerCamelCase ) shuffle(_lowerCamelCase ) return "".join(_lowerCamelCase ) # random is a generalised function for letters, characters and numbers def lowerCamelCase_ ( _lowerCamelCase : str , _lowerCamelCase : int ): return "".join(secrets.choice(_lowerCamelCase ) for _ in range(_lowerCamelCase ) ) def lowerCamelCase_ ( _lowerCamelCase : Dict , _lowerCamelCase : str ): pass # Put your code here... def lowerCamelCase_ ( _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[Any] ): pass # Put your code here... def lowerCamelCase_ ( _lowerCamelCase : int , _lowerCamelCase : str ): pass # Put your code here... def lowerCamelCase_ ( _lowerCamelCase : str , _lowerCamelCase : int = 8 ): if len(_lowerCamelCase ) < min_length: # Your Password must be at least 8 characters long return False lowerCamelCase_ = any(char in ascii_uppercase for char in password ) lowerCamelCase_ = any(char in ascii_lowercase for char in password ) lowerCamelCase_ = any(char in digits for char in password ) lowerCamelCase_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def lowerCamelCase_ ( ): lowerCamelCase_ = int(input('''Please indicate the max length of your password: ''' ).strip() ) lowerCamelCase_ = input( '''Please indicate the characters that must be in your password: ''' ).strip() print('''Password generated:''' , password_generator(_lowerCamelCase ) ) print( '''Alternative Password generated:''' , alternative_password_generator(_lowerCamelCase , _lowerCamelCase ) , ) print('''[If you are thinking of using this passsword, You better save it.]''' ) if __name__ == "__main__": main()
66
1
'''simple docstring''' def _A ( snake_case , snake_case , snake_case , snake_case ) -> int: _lowercase , _lowercase : Optional[Any] = len(snake_case ), len(grid[0] ) if ( min(snake_case , snake_case ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) _lowercase : Union[str, Any] = 0 count += depth_first_search(snake_case , row + 1 , snake_case , snake_case ) count += depth_first_search(snake_case , row - 1 , snake_case , snake_case ) count += depth_first_search(snake_case , snake_case , col + 1 , snake_case ) count += depth_first_search(snake_case , snake_case , col - 1 , snake_case ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
245
'''simple docstring''' import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() _snake_case = logging.get_logger(__name__) def _A ( snake_case ) -> str: _lowercase : Dict = torch.load(snake_case , map_location="cpu" ) if "model" in sd.keys(): _lowercase : Tuple = torch.load(snake_case , map_location="cpu" )["model"] # pop unnecessary weights _lowercase : Any = [ "decoder.version", "decoder.output_projection.weight", ] for key in keys_to_delete: if key in sd: sd.pop(snake_case ) _lowercase : List[Any] = { "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: _lowercase : Dict = sd.pop(snake_case ) _lowercase : List[str] = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: _lowercase : List[Any] = sd[key] # We split QKV in separate Q,K,V _lowercase : str = key.replace(".qkv_proj." , ".q_proj." ) _lowercase : List[str] = key.replace(".qkv_proj." , ".k_proj." ) _lowercase : Optional[Any] = key.replace(".qkv_proj." , ".v_proj." ) _lowercase : Union[str, Any] = 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 _lowercase , _lowercase , _lowercase : Dict = torch.split(snake_case , depth // 3 , dim=0 ) _lowercase : Optional[int] = q _lowercase : str = k _lowercase : List[str] = v del sd[key] return sd @torch.no_grad() def _A ( snake_case , snake_case , snake_case=None ) -> Any: _lowercase : Union[str, Any] = load_checkpoint(snake_case ) if config is not None: _lowercase : Tuple = OPTConfig.from_pretrained(snake_case ) else: _lowercase : Optional[int] = OPTConfig() _lowercase : List[Any] = OPTModel(snake_case ).half().eval() model.load_state_dict(snake_case ) # Check results Path(snake_case ).mkdir(exist_ok=snake_case ) model.save_pretrained(snake_case ) if __name__ == "__main__": _snake_case = 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.') _snake_case = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
245
1
"""simple docstring""" import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer SCREAMING_SNAKE_CASE : List[Any] = '''bart''' SCREAMING_SNAKE_CASE : Union[str, Any] = True @st.cache(allow_output_mutation=lowerCAmelCase__ ) def __lowerCamelCase ( ): if LOAD_DENSE_INDEX: A__ = AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased' ) A__ = AutoModel.from_pretrained('yjernite/retribert-base-uncased' ).to('cuda:0' ) A__ = qar_model.eval() else: A__ , A__ = (None, None) if MODEL_TYPE == "bart": A__ = AutoTokenizer.from_pretrained('yjernite/bart_eli5' ) A__ = AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5' ).to('cuda:0' ) A__ = torch.load('seq2seq_models/eli5_bart_model_blm_2.pth' ) sas_model.load_state_dict(save_dict['model'] ) A__ = sas_model.eval() else: A__ , A__ = make_qa_sas_model( model_name='t5-small' ,from_file='seq2seq_models/eli5_t5_model_1024_4.pth' ,device='cuda:0' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=lowerCAmelCase__ ) def __lowerCamelCase ( ): if LOAD_DENSE_INDEX: A__ = faiss.StandardGpuResources() A__ = datasets.load_dataset(path='wiki_snippets' ,name='wiki40b_en_100_0' )['train'] A__ = np.memmap( 'wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat' ,dtype='float32' ,mode='r' ,shape=(wikiaab_passages.num_rows, 128) ,) A__ = faiss.IndexFlatIP(128 ) A__ = faiss.index_cpu_to_gpu(lowerCAmelCase__ ,1 ,lowerCAmelCase__ ) wikiaab_gpu_index_flat.add(lowerCAmelCase__ ) # TODO fix for larger GPU else: A__ , A__ = (None, None) A__ = Elasticsearch([{'host': 'localhost', 'port': '9200'}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=lowerCAmelCase__ ) def __lowerCamelCase ( ): A__ = datasets.load_dataset('eli5' ,name='LFQA_reddit' ) A__ = elia['train_eli5'] A__ = np.memmap( 'eli5_questions_reps.dat' ,dtype='float32' ,mode='r' ,shape=(elia_train.num_rows, 128) ) A__ = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(lowerCAmelCase__ ) return (elia_train, eli5_train_q_index) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = load_indexes() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = load_models() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = load_train_data() def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__=10 ): A__ = embed_questions_for_retrieval([question] ,lowerCAmelCase__ ,lowerCAmelCase__ ) A__ , A__ = eli5_train_q_index.search(lowerCAmelCase__ ,lowerCAmelCase__ ) A__ = [elia_train[int(lowerCAmelCase__ )] for i in I[0]] return nn_examples def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__="wiki40b" ,lowerCAmelCase__="dense" ,lowerCAmelCase__=10 ): if source == "none": A__ , A__ = (' <P> '.join(['' for _ in range(11 )] ).strip(), []) else: if method == "dense": A__ , A__ = query_qa_dense_index( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) else: A__ , A__ = query_es_index( lowerCAmelCase__ ,lowerCAmelCase__ ,index_name='english_wiki40b_snippets_100w' ,n_results=lowerCAmelCase__ ,) A__ = [ (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst ] A__ = 'question: {} context: {}'.format(lowerCAmelCase__ ,lowerCAmelCase__ ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda lowerCAmelCase__ : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda lowerCAmelCase__ : None), } ) def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__=64 ,lowerCAmelCase__=256 ,lowerCAmelCase__=False ,lowerCAmelCase__=2 ,lowerCAmelCase__=0.9_5 ,lowerCAmelCase__=0.8 ): with torch.no_grad(): A__ = qa_sas_generate( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,num_answers=1 ,num_beams=lowerCAmelCase__ ,min_len=lowerCAmelCase__ ,max_len=lowerCAmelCase__ ,do_sample=lowerCAmelCase__ ,temp=lowerCAmelCase__ ,top_p=lowerCAmelCase__ ,top_k=lowerCAmelCase__ ,max_input_length=1024 ,device='cuda:0' ,)[0] return (answer, support_list) st.title('''Long Form Question Answering with ELI5''') # Start sidebar SCREAMING_SNAKE_CASE : str = '''<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>''' SCREAMING_SNAKE_CASE : List[Any] = ''' <html> <head> <style> .img-container { padding-left: 90px; padding-right: 90px; padding-top: 50px; padding-bottom: 50px; background-color: #f0f3f9; } </style> </head> <body> <span class="img-container"> <!-- Inline parent element --> %s </span> </body> </html> ''' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia SCREAMING_SNAKE_CASE : List[Any] = ''' This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html). First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset, a pre-processed fixed snapshot of Wikipedia. ''' st.sidebar.markdown(description, unsafe_allow_html=True) SCREAMING_SNAKE_CASE : Dict = [ '''Answer the question''', '''View the retrieved document only''', '''View the most similar ELI5 question and answer''', '''Show me everything, please!''', ] SCREAMING_SNAKE_CASE : Union[str, Any] = st.sidebar.checkbox('''Demo options''') if demo_options: SCREAMING_SNAKE_CASE : Union[str, Any] = st.sidebar.selectbox( '''''', action_list, index=3, ) SCREAMING_SNAKE_CASE : Dict = action_list.index(action_st) SCREAMING_SNAKE_CASE : Optional[int] = st.sidebar.selectbox( '''''', ['''Show full text of passages''', '''Show passage section titles'''], index=0, ) SCREAMING_SNAKE_CASE : Union[str, Any] = show_type == '''Show full text of passages''' else: SCREAMING_SNAKE_CASE : Union[str, Any] = 3 SCREAMING_SNAKE_CASE : Any = True SCREAMING_SNAKE_CASE : Dict = st.sidebar.checkbox('''Retrieval options''') if retrieval_options: SCREAMING_SNAKE_CASE : int = ''' ### Information retriever options The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs. The answer is then generated by sequence to sequence model which takes the question and retrieved document as input. ''' st.sidebar.markdown(retriever_info) SCREAMING_SNAKE_CASE : Dict = st.sidebar.selectbox('''Which Wikipedia format should the model use?''', ['''wiki40b''', '''none''']) SCREAMING_SNAKE_CASE : Optional[Any] = st.sidebar.selectbox('''Which Wikipedia indexer should the model use?''', ['''dense''', '''sparse''', '''mixed''']) else: SCREAMING_SNAKE_CASE : Tuple = '''wiki40b''' SCREAMING_SNAKE_CASE : List[str] = '''dense''' SCREAMING_SNAKE_CASE : str = '''beam''' SCREAMING_SNAKE_CASE : Tuple = 2 SCREAMING_SNAKE_CASE : Union[str, Any] = 64 SCREAMING_SNAKE_CASE : Tuple = 256 SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : Dict = None SCREAMING_SNAKE_CASE : Dict = st.sidebar.checkbox('''Generation options''') if generate_options: SCREAMING_SNAKE_CASE : Optional[Any] = ''' ### Answer generation options The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large) weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with **beam** search, or **sample** from the decoder\'s output probabilities. ''' st.sidebar.markdown(generate_info) SCREAMING_SNAKE_CASE : Dict = st.sidebar.selectbox('''Would you like to use beam search or sample an answer?''', ['''beam''', '''sampled''']) SCREAMING_SNAKE_CASE : Any = st.sidebar.slider( '''Minimum generation length''', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) SCREAMING_SNAKE_CASE : int = st.sidebar.slider( '''Maximum generation length''', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": SCREAMING_SNAKE_CASE : Any = st.sidebar.slider('''Beam size''', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: SCREAMING_SNAKE_CASE : Union[str, Any] = st.sidebar.slider( '''Nucleus sampling p''', min_value=0.1, max_value=1.0, value=0.9_5, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE : Tuple = st.sidebar.slider( '''Temperature''', min_value=0.1, max_value=1.0, value=0.7, step=0.0_1, format=None, key=None ) SCREAMING_SNAKE_CASE : List[str] = None # start main text SCREAMING_SNAKE_CASE : Dict = [ '''<MY QUESTION>''', '''How do people make chocolate?''', '''Why do we get a fever when we are sick?''', '''How can different animals perceive different colors?''', '''What is natural language processing?''', '''What\'s the best way to treat a sunburn?''', '''What exactly are vitamins ?''', '''How does nuclear energy provide electricity?''', '''What\'s the difference between viruses and bacteria?''', '''Why are flutes classified as woodwinds when most of them are made out of metal ?''', '''Why do people like drinking coffee even though it tastes so bad?''', '''What happens when wine ages? How does it make the wine taste better?''', '''If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?''', '''How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?''', '''How does New Zealand have so many large bird predators?''', ] SCREAMING_SNAKE_CASE : Tuple = st.selectbox( '''What would you like to ask? ---- select <MY QUESTION> to enter a new query''', questions_list, index=1, ) if question_s == "<MY QUESTION>": SCREAMING_SNAKE_CASE : Tuple = st.text_input('''Enter your question here:''', '''''') else: SCREAMING_SNAKE_CASE : List[Any] = question_s if st.button('''Show me!'''): if action in [0, 1, 3]: if index_type == "mixed": SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = make_support(question, source=wiki_source, method='''dense''', n_results=10) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = make_support(question, source=wiki_source, method='''sparse''', n_results=10) SCREAMING_SNAKE_CASE : Any = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] SCREAMING_SNAKE_CASE : int = support_list[:10] SCREAMING_SNAKE_CASE : str = '''<P> ''' + ''' <P> '''.join([res[-1] for res in support_list]) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == '''sampled'''), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('''### The model generated answer is:''') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('''--- \n ### The model is drawing information from the following Wikipedia passages:''') for i, res in enumerate(support_list): SCREAMING_SNAKE_CASE : str = '''https://en.wikipedia.org/wiki/{}'''.format(res[0].replace(''' ''', '''_''')) SCREAMING_SNAKE_CASE : str = res[1].strip() if sec_titles == "": SCREAMING_SNAKE_CASE : List[Any] = '''[{}]({})'''.format(res[0], wiki_url) else: SCREAMING_SNAKE_CASE : int = sec_titles.split(''' & ''') SCREAMING_SNAKE_CASE : List[Any] = ''' & '''.join( ['''[{}]({}#{})'''.format(sec.strip(), wiki_url, sec.strip().replace(''' ''', '''_''')) for sec in sec_list] ) st.markdown( '''{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'''.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '''> <span style="font-family:arial; font-size:10pt;">''' + res[-1] + '''</span>''', unsafe_allow_html=True ) if action in [2, 3]: SCREAMING_SNAKE_CASE : Tuple = find_nearest_training(question) SCREAMING_SNAKE_CASE : Dict = nn_train_list[0] st.markdown( '''--- \n ### The most similar question in the ELI5 training set was: \n\n {}'''.format(train_exple['''title''']) ) SCREAMING_SNAKE_CASE : List[Any] = [ '''{}. {}'''.format(i + 1, ''' \n'''.join([line.strip() for line in ans.split('''\n''') if line.strip() != ''''''])) for i, (ans, sc) in enumerate(zip(train_exple['''answers''']['''text'''], train_exple['''answers''']['''score'''])) if i == 0 or sc > 2 ] st.markdown('''##### Its answers were: \n\n {}'''.format('''\n'''.join(answers_st))) SCREAMING_SNAKE_CASE : str = ''' --- **Disclaimer** *The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system. Evaluating biases of such a model and ensuring factual generations are still very much open research problems. Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.* ''' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
554
"""simple docstring""" class snake_case_ : """simple docstring""" def __init__( self , __a , __a ): """simple docstring""" A__ = name A__ = val def __str__( self ): """simple docstring""" return f'''{self.__class__.__name__}({self.name}, {self.val})''' def __lt__( self , __a ): """simple docstring""" return self.val < other.val class snake_case_ : """simple docstring""" def __init__( self , __a ): """simple docstring""" A__ = {} A__ = {} A__ = self.build_heap(__a ) def __getitem__( self , __a ): """simple docstring""" return self.get_value(__a ) def _UpperCAmelCase ( self , __a ): """simple docstring""" return (idx - 1) // 2 def _UpperCAmelCase ( self , __a ): """simple docstring""" return idx * 2 + 1 def _UpperCAmelCase ( self , __a ): """simple docstring""" return idx * 2 + 2 def _UpperCAmelCase ( self , __a ): """simple docstring""" return self.heap_dict[key] def _UpperCAmelCase ( self , __a ): """simple docstring""" A__ = len(__a ) - 1 A__ = self.get_parent_idx(__a ) for idx, i in enumerate(__a ): A__ = idx A__ = i.val for i in range(__a , -1 , -1 ): self.sift_down(__a , __a ) return array def _UpperCAmelCase ( self , __a , __a ): """simple docstring""" while True: A__ = self.get_left_child_idx(__a ) # noqa: E741 A__ = self.get_right_child_idx(__a ) A__ = idx if l < len(__a ) and array[l] < array[idx]: A__ = l if r < len(__a ) and array[r] < array[smallest]: A__ = r if smallest != idx: A__ , A__ = array[smallest], array[idx] ( ( A__ ) , ( A__ ) , ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) A__ = smallest else: break def _UpperCAmelCase ( self , __a ): """simple docstring""" A__ = self.get_parent_idx(__a ) while p >= 0 and self.heap[p] > self.heap[idx]: A__ , A__ = self.heap[idx], self.heap[p] A__ , A__ = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) A__ = p A__ = self.get_parent_idx(__a ) def _UpperCAmelCase ( self ): """simple docstring""" return self.heap[0] def _UpperCAmelCase ( self ): """simple docstring""" A__ , A__ = self.heap[-1], self.heap[0] A__ , A__ = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) A__ = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def _UpperCAmelCase ( self , __a ): """simple docstring""" self.heap.append(__a ) A__ = len(self.heap ) - 1 A__ = node.val self.sift_up(len(self.heap ) - 1 ) def _UpperCAmelCase ( self ): """simple docstring""" return len(self.heap ) == 0 def _UpperCAmelCase ( self , __a , __a ): """simple docstring""" assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" A__ = new_value A__ = new_value self.sift_up(self.idx_of_element[node] ) SCREAMING_SNAKE_CASE : List[str] = Node('''R''', -1) SCREAMING_SNAKE_CASE : Tuple = Node('''B''', 6) SCREAMING_SNAKE_CASE : List[Any] = Node('''A''', 3) SCREAMING_SNAKE_CASE : int = Node('''X''', 1) SCREAMING_SNAKE_CASE : Union[str, Any] = Node('''E''', 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array SCREAMING_SNAKE_CASE : str = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print('''Min Heap - before decrease key''') for i in my_min_heap.heap: print(i) print('''Min Heap - After decrease key of node [B -> -17]''') my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
554
1
import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def lowerCamelCase__ ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : str=() , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[str]="no" , __lowerCamelCase : Dict="29500" ): __UpperCAmelCase : int = False __UpperCAmelCase : List[Any] = False if any(key.startswith("""KAGGLE""" ) for key in os.environ.keys() ): __UpperCAmelCase : Any = True elif "IPython" in sys.modules: __UpperCAmelCase : Optional[Any] = """google.colab""" in str(sys.modules["""IPython"""].get_ipython() ) try: __UpperCAmelCase : Dict = PrecisionType(mixed_precision.lower() ) except ValueError: raise ValueError( f"""Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.""" ) if (in_colab or in_kaggle) and (os.environ.get("""TPU_NAME""" , __lowerCamelCase ) is not None): # TPU launch import torch_xla.distributed.xla_multiprocessing as xmp if len(AcceleratorState._shared_state ) > 0: raise ValueError( """To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside """ """your training function. Restart your notebook and make sure no cells initializes an """ """`Accelerator`.""" ) if num_processes is None: __UpperCAmelCase : int = 8 __UpperCAmelCase : Optional[Any] = PrepareForLaunch(__lowerCamelCase , distributed_type="""TPU""" ) print(f"""Launching a training on {num_processes} TPU cores.""" ) xmp.spawn(__lowerCamelCase , args=__lowerCamelCase , nprocs=__lowerCamelCase , start_method="""fork""" ) elif in_colab: # No need for a distributed launch otherwise as it's either CPU or one GPU. if torch.cuda.is_available(): print("""Launching training on one GPU.""" ) else: print("""Launching training on one CPU.""" ) function(*__lowerCamelCase ) else: if num_processes is None: raise ValueError( """You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.""" ) if num_processes > 1: # Multi-GPU launch from torch.multiprocessing import start_processes from torch.multiprocessing.spawn import ProcessRaisedException if len(AcceleratorState._shared_state ) > 0: raise ValueError( """To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized """ """inside your training function. Restart your notebook and make sure no cells initializes an """ """`Accelerator`.""" ) if torch.cuda.is_initialized(): raise ValueError( """To launch a multi-GPU training from your notebook, you need to avoid running any instruction """ """using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA """ """function.""" ) # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=__lowerCamelCase , master_addr="""127.0.01""" , master_port=__lowerCamelCase , mixed_precision=__lowerCamelCase ): __UpperCAmelCase : Dict = PrepareForLaunch(__lowerCamelCase , distributed_type="""MULTI_GPU""" ) print(f"""Launching training on {num_processes} GPUs.""" ) try: start_processes(__lowerCamelCase , args=__lowerCamelCase , nprocs=__lowerCamelCase , start_method="""fork""" ) except ProcessRaisedException as e: if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: raise RuntimeError( """CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. """ """This likely stems from an outside import causing issues once the `notebook_launcher()` is called. """ """Please review your imports and test them when running the `notebook_launcher()` to identify """ """which one is problematic.""" ) from e else: # No need for a distributed launch otherwise as it's either CPU, GPU or MPS. if is_mps_available(): __UpperCAmelCase : Union[str, Any] = """1""" print("""Launching training on MPS.""" ) elif torch.cuda.is_available(): print("""Launching training on one GPU.""" ) else: print("""Launching training on CPU.""" ) function(*__lowerCamelCase ) def lowerCamelCase__ ( __lowerCamelCase : str , __lowerCamelCase : List[Any]=() , __lowerCamelCase : Dict=2 ): from torch.multiprocessing import start_processes with tempfile.NamedTemporaryFile() as tmp_file: # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=__lowerCamelCase , master_addr="""127.0.01""" , master_port="""29500""" , accelerate_mixed_precision="""no""" , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu="""yes""" , ): __UpperCAmelCase : Tuple = PrepareForLaunch(__lowerCamelCase , debug=__lowerCamelCase ) start_processes(__lowerCamelCase , args=__lowerCamelCase , nprocs=__lowerCamelCase , start_method="""fork""" )
63
"""simple docstring""" import requests _A = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def lowercase (_snake_case ) -> None: '''simple docstring''' __UpperCamelCase = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["articles"] ,1 ): print(f"""{i}.) {article["title"]}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
505
0
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class UpperCamelCase__ : '''simple docstring''' @staticmethod def UpperCamelCase_ ( *_lowerCAmelCase ,**_lowerCAmelCase ): pass @is_pipeline_test @require_vision class UpperCamelCase__ (unittest.TestCase ): '''simple docstring''' @require_torch def UpperCamelCase_ ( self ): lowerCamelCase__ = pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" ,) lowerCamelCase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCamelCase__ = image_classifier(UpperCAmelCase__ ,candidate_labels=["""a""", """b""", """c"""] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(UpperCAmelCase__ ) ,[ [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}], [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """c"""}, {"""score""": 0.333, """label""": """b"""}], ] ,) lowerCamelCase__ = image_classifier([image] * 5 ,candidate_labels=["""A""", """B""", """C"""] ,batch_size=2 ) self.assertEqual( nested_simplify(UpperCAmelCase__ ) ,[ [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, ], ] ,) @require_tf def UpperCamelCase_ ( self ): lowerCamelCase__ = pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" ,framework="""tf""" ) lowerCamelCase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCamelCase__ = image_classifier(UpperCAmelCase__ ,candidate_labels=["""a""", """b""", """c"""] ) self.assertEqual( nested_simplify(UpperCAmelCase__ ) ,[{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}] ,) lowerCamelCase__ = image_classifier([image] * 5 ,candidate_labels=["""A""", """B""", """C"""] ,batch_size=2 ) self.assertEqual( nested_simplify(UpperCAmelCase__ ) ,[ [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase__ )}, ], ] ,) @slow @require_torch def UpperCamelCase_ ( self ): lowerCamelCase__ = pipeline( task="""zero-shot-image-classification""" ,model="""openai/clip-vit-base-patch32""" ,) # This is an image of 2 cats with remotes and no planes lowerCamelCase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCamelCase__ = image_classifier(UpperCAmelCase__ ,candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(UpperCAmelCase__ ) ,[ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ] ,) lowerCamelCase__ = image_classifier([image] * 5 ,candidate_labels=["""cat""", """plane""", """remote"""] ,batch_size=2 ) self.assertEqual( nested_simplify(UpperCAmelCase__ ) ,[ [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ], ] * 5 ,) @slow @require_tf def UpperCamelCase_ ( self ): lowerCamelCase__ = pipeline( task="""zero-shot-image-classification""" ,model="""openai/clip-vit-base-patch32""" ,framework="""tf""" ) # This is an image of 2 cats with remotes and no planes lowerCamelCase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCamelCase__ = image_classifier(UpperCAmelCase__ ,candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(UpperCAmelCase__ ) ,[ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ] ,) lowerCamelCase__ = image_classifier([image] * 5 ,candidate_labels=["""cat""", """plane""", """remote"""] ,batch_size=2 ) self.assertEqual( nested_simplify(UpperCAmelCase__ ) ,[ [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ], ] * 5 ,)
720
'''simple docstring''' import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class UpperCamelCase__ (unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ): lowerCamelCase__ = tempfile.mkdtemp() lowerCamelCase__ = BlipImageProcessor() lowerCamelCase__ = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-BertModel""" ) lowerCamelCase__ = BlipProcessor(_lowerCAmelCase ,_lowerCAmelCase ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self ,**_lowerCAmelCase ): return AutoProcessor.from_pretrained(self.tmpdirname ,**_lowerCAmelCase ).tokenizer def UpperCamelCase_ ( self ,**_lowerCAmelCase ): return AutoProcessor.from_pretrained(self.tmpdirname ,**_lowerCAmelCase ).image_processor def UpperCamelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self ): lowerCamelCase__ = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] lowerCamelCase__ = [Image.fromarray(np.moveaxis(_lowerCAmelCase ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self ): lowerCamelCase__ = BlipProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase__ = self.get_tokenizer(bos_token="""(BOS)""" ,eos_token="""(EOS)""" ) lowerCamelCase__ = self.get_image_processor(do_normalize=_lowerCAmelCase ,padding_value=1.0 ) lowerCamelCase__ = BlipProcessor.from_pretrained( self.tmpdirname ,bos_token="""(BOS)""" ,eos_token="""(EOS)""" ,do_normalize=_lowerCAmelCase ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,_lowerCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,_lowerCAmelCase ) def UpperCamelCase_ ( self ): lowerCamelCase__ = self.get_image_processor() lowerCamelCase__ = self.get_tokenizer() lowerCamelCase__ = BlipProcessor(tokenizer=_lowerCAmelCase ,image_processor=_lowerCAmelCase ) lowerCamelCase__ = self.prepare_image_inputs() lowerCamelCase__ = image_processor(_lowerCAmelCase ,return_tensors="""np""" ) lowerCamelCase__ = processor(images=_lowerCAmelCase ,return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1E-2 ) def UpperCamelCase_ ( self ): lowerCamelCase__ = self.get_image_processor() lowerCamelCase__ = self.get_tokenizer() lowerCamelCase__ = BlipProcessor(tokenizer=_lowerCAmelCase ,image_processor=_lowerCAmelCase ) lowerCamelCase__ = """lower newer""" lowerCamelCase__ = processor(text=_lowerCAmelCase ) lowerCamelCase__ = tokenizer(_lowerCAmelCase ,return_token_type_ids=_lowerCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def UpperCamelCase_ ( self ): lowerCamelCase__ = self.get_image_processor() lowerCamelCase__ = self.get_tokenizer() lowerCamelCase__ = BlipProcessor(tokenizer=_lowerCAmelCase ,image_processor=_lowerCAmelCase ) lowerCamelCase__ = """lower newer""" lowerCamelCase__ = self.prepare_image_inputs() lowerCamelCase__ = processor(text=_lowerCAmelCase ,images=_lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) ,["""pixel_values""", """input_ids""", """attention_mask"""] ) # test if it raises when no input is passed with pytest.raises(_lowerCAmelCase ): processor() def UpperCamelCase_ ( self ): lowerCamelCase__ = self.get_image_processor() lowerCamelCase__ = self.get_tokenizer() lowerCamelCase__ = BlipProcessor(tokenizer=_lowerCAmelCase ,image_processor=_lowerCAmelCase ) lowerCamelCase__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCamelCase__ = processor.batch_decode(_lowerCAmelCase ) lowerCamelCase__ = tokenizer.batch_decode(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase ,_lowerCAmelCase ) def UpperCamelCase_ ( self ): lowerCamelCase__ = self.get_image_processor() lowerCamelCase__ = self.get_tokenizer() lowerCamelCase__ = BlipProcessor(tokenizer=_lowerCAmelCase ,image_processor=_lowerCAmelCase ) lowerCamelCase__ = """lower newer""" lowerCamelCase__ = self.prepare_image_inputs() lowerCamelCase__ = processor(text=_lowerCAmelCase ,images=_lowerCAmelCase ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) ,["""pixel_values""", """input_ids""", """attention_mask"""] )
9
0
from collections.abc import Generator def UpperCamelCase ( ): """simple docstring""" __magic_name__ ,__magic_name__ : Any = 0, 1 while True: __magic_name__ ,__magic_name__ : Dict = b, a + b yield b def UpperCamelCase ( _A = 1000 ): """simple docstring""" __magic_name__ : Optional[Any] = 1 __magic_name__ : Optional[int] = fibonacci_generator() while len(str(next(__a ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
324
from sklearn.metrics import mean_squared_error import datasets lowerCamelCase__ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' lowerCamelCase__ = '''\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. ''' lowerCamelCase__ = ''' Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {\'mse\': 0.6123724356957945} If you\'re using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mse\': array([0.41666667, 1. ])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ (datasets.Metric ): def __a ( self ) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html" ] , ) def __a ( self ) -> Union[str, Any]: if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("float" ) ), "references": datasets.Sequence(datasets.Value("float" ) ), } else: return { "predictions": datasets.Value("float" ), "references": datasets.Value("float" ), } def __a ( self , _a , _a , _a=None , _a="uniform_average" , _a=True ) -> Dict: lowerCAmelCase_ = mean_squared_error( _a , _a , sample_weight=_a , multioutput=_a , squared=_a ) return {"mse": mse}
122
0
def _lowerCAmelCase (_lowerCAmelCase = 10_00): UpperCamelCase_ = 2**power UpperCamelCase_ = 0 while n: UpperCamelCase_ , UpperCamelCase_ = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
504
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : str =logging.get_logger(__name__) UpperCAmelCase : Tuple ={ """google/pegasus-large""": """https://huggingface.co/google/pegasus-large/resolve/main/config.json""", # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class _lowercase (a_ ): '''simple docstring''' lowercase__ = """pegasus""" lowercase__ = ["""past_key_values"""] lowercase__ = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , snake_case__=5_0265 , snake_case__=1024 , snake_case__=12 , snake_case__=4096 , snake_case__=16 , snake_case__=12 , snake_case__=4096 , snake_case__=16 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=True , snake_case__=True , snake_case__="gelu" , snake_case__=1024 , snake_case__=0.1 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=0.02 , snake_case__=0 , snake_case__=False , snake_case__=0 , snake_case__=1 , snake_case__=1 , **snake_case__ , ): '''simple docstring''' UpperCamelCase_ = vocab_size UpperCamelCase_ = max_position_embeddings UpperCamelCase_ = d_model UpperCamelCase_ = encoder_ffn_dim UpperCamelCase_ = encoder_layers UpperCamelCase_ = encoder_attention_heads UpperCamelCase_ = decoder_ffn_dim UpperCamelCase_ = decoder_layers UpperCamelCase_ = decoder_attention_heads UpperCamelCase_ = dropout UpperCamelCase_ = attention_dropout UpperCamelCase_ = activation_dropout UpperCamelCase_ = activation_function UpperCamelCase_ = init_std UpperCamelCase_ = encoder_layerdrop UpperCamelCase_ = decoder_layerdrop UpperCamelCase_ = use_cache UpperCamelCase_ = encoder_layers UpperCamelCase_ = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=snake_case__ , eos_token_id=snake_case__ , is_encoder_decoder=snake_case__ , decoder_start_token_id=snake_case__ , forced_eos_token_id=snake_case__ , **snake_case__ , ) @property def _lowerCamelCase ( self ): '''simple docstring''' return self.encoder_attention_heads @property def _lowerCamelCase ( self ): '''simple docstring''' return self.d_model
504
1
def a (_lowerCAmelCase , _lowerCAmelCase ): if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
234
from __future__ import annotations _lowercase : Optional[int] =1.6021E-19 # units = C def lowerCAmelCase_ ( _lowercase : float , _lowercase : float , _lowercase : float , ) -> tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0) != 1: raise ValueError("""You cannot supply more or less than 2 values""") elif conductivity < 0: raise ValueError("""Conductivity cannot be negative""") elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative""") elif mobility < 0: raise ValueError("""mobility cannot be negative""") elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
136
0
'''simple docstring''' import heapq import sys import numpy as np UpperCamelCase__ = tuple[int, int] class _UpperCAmelCase : def __init__( self : Optional[int] ): '''simple docstring''' lowercase_ : List[str] = [] lowercase_ : List[str] = set() def lowerCAmelCase__ ( self : List[str] ): '''simple docstring''' if not self.empty(): return self.elements[0][0] else: return float("inf" ) def lowerCAmelCase__ ( self : Optional[Any] ): '''simple docstring''' return len(self.elements ) == 0 def lowerCAmelCase__ ( self : Any , a : List[Any] , a : Tuple ): '''simple docstring''' if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(a ) else: # update # print("update", item) lowercase_ : int = [] (lowercase_) : Any = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) (lowercase_) : List[Any] = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def lowerCAmelCase__ ( self : Optional[int] , a : List[str] ): '''simple docstring''' if item in self.set: self.set.remove(a ) lowercase_ : Optional[Any] = [] (lowercase_) : List[Any] = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) (lowercase_) : Dict = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def lowerCAmelCase__ ( self : str ): '''simple docstring''' return self.elements[0][1] def lowerCAmelCase__ ( self : Optional[int] ): '''simple docstring''' (lowercase_) : Optional[Any] = heapq.heappop(self.elements ) self.set.remove(a ) return (priority, item) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" lowercase_ : int = np.array(_UpperCamelCase ) lowercase_ : Optional[int] = np.array(_UpperCamelCase ) return np.linalg.norm(a - b ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" return consistent_heuristic(_UpperCamelCase , _UpperCamelCase ) // t def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" lowercase_ : List[Any] = g_function[start] + Wa * heuristics[i](_UpperCamelCase , _UpperCamelCase ) return ans def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" lowercase_ : Dict = np.chararray((n, n) ) for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): lowercase_ : List[str] = "*" for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): if (j, (n - 1) - i) in blocks: lowercase_ : int = "#" lowercase_ : Optional[int] = "-" lowercase_ : List[Any] = back_pointer[goal] while x != start: (lowercase_) : Any = x # print(x) lowercase_ : Dict = "-" lowercase_ : str = back_pointer[x] lowercase_ : Any = "-" for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): if (i, j) == (0, n - 1): print(grid[i][j] , end=" " ) print("<-- End position" , end=" " ) else: print(grid[i][j] , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) print("PATH TAKEN BY THE ALGORITHM IS:-" ) lowercase_ : Dict = back_pointer[goal] while x != start: print(_UpperCamelCase , end=" " ) lowercase_ : Dict = back_pointer[x] print(_UpperCamelCase ) sys.exit() def __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): """simple docstring""" if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ): """simple docstring""" for itera in range(_UpperCamelCase ): open_list[itera].remove_element(_UpperCamelCase ) # print("s", s) # print("j", j) (lowercase_) : Dict = s lowercase_ : Union[str, Any] = (x - 1, y) lowercase_ : Tuple = (x + 1, y) lowercase_ : str = (x, y + 1) lowercase_ : Dict = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(_UpperCamelCase ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(_UpperCamelCase ) lowercase_ : Union[str, Any] = -1 lowercase_ : List[str] = float("inf" ) if valid(_UpperCamelCase ) and g_function[neighbours] > g_function[s] + 1: lowercase_ : Dict = g_function[s] + 1 lowercase_ : Optional[Any] = s if neighbours not in close_list_anchor: open_list[0].put(_UpperCamelCase , key(_UpperCamelCase , 0 , _UpperCamelCase , _UpperCamelCase ) ) if neighbours not in close_list_inad: for var in range(1 , _UpperCamelCase ): if key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) <= Wa * key( _UpperCamelCase , 0 , _UpperCamelCase , _UpperCamelCase ): open_list[j].put( _UpperCamelCase , key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) ) def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" lowercase_ : Any = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list UpperCamelCase__ = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} UpperCamelCase__ = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] UpperCamelCase__ = make_common_ground() UpperCamelCase__ = blocks_blk # hyper parameters UpperCamelCase__ = 1 UpperCamelCase__ = 1 UpperCamelCase__ = 20 UpperCamelCase__ = 3 # one consistent and two other inconsistent # start and end destination UpperCamelCase__ = (0, 0) UpperCamelCase__ = (n - 1, n - 1) UpperCamelCase__ = 1 def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" lowercase_ : List[str] = {start: 0, goal: float("inf" )} lowercase_ : Any = {start: -1, goal: -1} lowercase_ : List[Any] = [] lowercase_ : Dict = set() for i in range(_UpperCamelCase ): open_list.append(PriorityQueue() ) open_list[i].put(_UpperCamelCase , key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) ) lowercase_ : list[int] = [] lowercase_ : list[int] = [] while open_list[0].minkey() < float("inf" ): for i in range(1 , _UpperCamelCase ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("inf" ): do_something(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) else: lowercase_ : int = open_list[i].top_show() visited.add(_UpperCamelCase ) expand_state( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) close_list_inad.append(_UpperCamelCase ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("inf" ): do_something(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) else: lowercase_ : List[str] = open_list[0].top_show() visited.add(_UpperCamelCase ) expand_state( _UpperCamelCase , 0 , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) close_list_anchor.append(_UpperCamelCase ) print("No path found to goal" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(_UpperCamelCase ): if (j, i) in blocks: print("#" , end=" " ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("*" , end=" " ) else: print("-" , end=" " ) else: print("*" , end=" " ) if (j, i) == (n - 1, n - 1): print("<-- End position" , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
709
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _UpperCAmelCase ( snake_case , unittest.TestCase ): __lowerCamelCase: Dict = KandinskyVaaPriorPipeline __lowerCamelCase: Optional[int] = ['prompt'] __lowerCamelCase: Any = ['prompt', 'negative_prompt'] __lowerCamelCase: List[Any] = [ 'num_images_per_prompt', 'generator', 'num_inference_steps', 'latents', 'negative_prompt', 'guidance_scale', 'output_type', 'return_dict', ] __lowerCamelCase: List[Any] = False @property def lowerCAmelCase__ ( self : Optional[Any] ): '''simple docstring''' return 3_2 @property def lowerCAmelCase__ ( self : Any ): '''simple docstring''' return 3_2 @property def lowerCAmelCase__ ( self : Any ): '''simple docstring''' return self.time_input_dim @property def lowerCAmelCase__ ( self : str ): '''simple docstring''' return self.time_input_dim * 4 @property def lowerCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' return 1_0_0 @property def lowerCAmelCase__ ( self : List[Any] ): '''simple docstring''' lowercase_ : Any = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def lowerCAmelCase__ ( self : Optional[Any] ): '''simple docstring''' torch.manual_seed(0 ) lowercase_ : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModelWithProjection(a ) @property def lowerCAmelCase__ ( self : Tuple ): '''simple docstring''' torch.manual_seed(0 ) lowercase_ : List[str] = { "num_attention_heads": 2, "attention_head_dim": 1_2, "embedding_dim": self.text_embedder_hidden_size, "num_layers": 1, } lowercase_ : Union[str, Any] = PriorTransformer(**a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 lowercase_ : List[Any] = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def lowerCAmelCase__ ( self : Tuple ): '''simple docstring''' torch.manual_seed(0 ) lowercase_ : Dict = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=2_2_4 , projection_dim=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1_4 , ) lowercase_ : Optional[Any] = CLIPVisionModelWithProjection(a ) return model @property def lowerCAmelCase__ ( self : List[str] ): '''simple docstring''' lowercase_ : List[str] = CLIPImageProcessor( crop_size=2_2_4 , do_center_crop=a , do_normalize=a , do_resize=a , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=2_2_4 , ) return image_processor def lowerCAmelCase__ ( self : List[str] ): '''simple docstring''' lowercase_ : Any = self.dummy_prior lowercase_ : Optional[Any] = self.dummy_image_encoder lowercase_ : List[Any] = self.dummy_text_encoder lowercase_ : Any = self.dummy_tokenizer lowercase_ : Optional[Any] = self.dummy_image_processor lowercase_ : List[str] = UnCLIPScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1_0_0_0 , clip_sample=a , clip_sample_range=10.0 , ) lowercase_ : List[Any] = { "prior": prior, "image_encoder": image_encoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "scheduler": scheduler, "image_processor": image_processor, } return components def lowerCAmelCase__ ( self : Any , a : Dict , a : Dict=0 ): '''simple docstring''' if str(a ).startswith("mps" ): lowercase_ : int = torch.manual_seed(a ) else: lowercase_ : Optional[Any] = torch.Generator(device=a ).manual_seed(a ) lowercase_ : Any = { "prompt": "horse", "generator": generator, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def lowerCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' lowercase_ : str = "cpu" lowercase_ : Any = self.get_dummy_components() lowercase_ : int = self.pipeline_class(**a ) lowercase_ : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) lowercase_ : Any = pipe(**self.get_dummy_inputs(a ) ) lowercase_ : List[Any] = output.image_embeds lowercase_ : str = pipe( **self.get_dummy_inputs(a ) , return_dict=a , )[0] lowercase_ : Any = image[0, -1_0:] lowercase_ : Dict = image_from_tuple[0, -1_0:] assert image.shape == (1, 3_2) lowercase_ : int = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def lowerCAmelCase__ ( self : Optional[Any] ): '''simple docstring''' lowercase_ : int = torch_device == "cpu" lowercase_ : Tuple = True lowercase_ : str = False self._test_inference_batch_single_identical( test_max_difference=a , relax_max_difference=a , test_mean_pixel_difference=a , ) @skip_mps def lowerCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' lowercase_ : Any = torch_device == "cpu" lowercase_ : int = False self._test_attention_slicing_forward_pass( test_max_difference=a , test_mean_pixel_difference=a , )
640
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __lowerCAmelCase : Dict ={} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Union[str, Any] =["BartphoTokenizer"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys __lowerCAmelCase : Union[str, Any] =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
440
'''simple docstring''' import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : Any =logging.get_logger(__name__) __lowerCAmelCase : int ="https://openaipublic.azureedge.net/jukebox/models/" __lowerCAmelCase : Any ={ "jukebox-1b-lyrics": [ "5b/vqvae.pth.tar", "5b/prior_level_0.pth.tar", "5b/prior_level_1.pth.tar", "1b_lyrics/prior_level_2.pth.tar", ], "jukebox-5b-lyrics": [ "5b/vqvae.pth.tar", "5b/prior_level_0.pth.tar", "5b/prior_level_1.pth.tar", "5b_lyrics/prior_level_2.pth.tar", ], } def UpperCamelCase ( _lowerCamelCase : str ): if key.endswith(".model.1.bias" ) and len(key.split("." ) ) > 10: A__ = key.replace(".model.1.bias" , ".conv1d_1.bias" ) elif key.endswith(".model.1.weight" ) and len(key.split("." ) ) > 10: A__ = key.replace(".model.1.weight" , ".conv1d_1.weight" ) elif key.endswith(".model.3.bias" ) and len(key.split("." ) ) > 10: A__ = key.replace(".model.3.bias" , ".conv1d_2.bias" ) elif key.endswith(".model.3.weight" ) and len(key.split("." ) ) > 10: A__ = key.replace(".model.3.weight" , ".conv1d_2.weight" ) if "conditioner_blocks.0." in key: A__ = key.replace("conditioner_blocks.0" , "conditioner_blocks" ) if "prime_prior" in key: A__ = key.replace("prime_prior" , "encoder" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: A__ = key.replace(".emb." , "." ) if key.endswith("k" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(".k" , ".codebook" ) if "y_emb." in key: return key.replace("y_emb." , "metadata_embedding." ) if "x_emb.emb." in key: A__ = key.replace("0.x_emb.emb" , "embed_tokens" ) if "prime_state_ln" in key: return key.replace("prime_state_ln" , "encoder.final_layer_norm" ) if ".ln" in key: return key.replace(".ln" , ".layer_norm" ) if "_ln" in key: return key.replace("_ln" , "_layer_norm" ) if "prime_state_proj" in key: return key.replace("prime_state_proj" , "encoder.proj_in" ) if "prime_x_out" in key: return key.replace("prime_x_out" , "encoder.lm_head" ) if "prior.x_out" in key: return key.replace("x_out" , "fc_proj_out" ) if "x_emb" in key: return key.replace("x_emb" , "embed_tokens" ) return key def UpperCamelCase ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str ): A__ = {} import re A__ = re.compile(r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)" ) A__ = re.compile( r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) A__ = re.compile(r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)" ) A__ = re.compile(r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)" ) A__ = re.compile( r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) A__ = re.compile(r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)" ) A__ = re.compile(r"conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)" ) A__ = re.compile( r"conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) A__ = re.compile(r"conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_lowerCamelCase ): A__ = re_encoder_block_conv_in.match(_lowerCamelCase ) A__ = regex_match.groups() A__ = int(groups[2] ) * 2 + int(groups[3] ) A__ = F"encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}" A__ = re_encoder_block_conv_in.sub(_lowerCamelCase , _lowerCamelCase ) elif re_encoder_block_resnet.fullmatch(_lowerCamelCase ): A__ = re_encoder_block_resnet.match(_lowerCamelCase ) A__ = regex_match.groups() A__ = int(groups[2] ) * 2 + int(groups[3] ) A__ = {"1": 1, "3": 2}[groups[-2]] A__ = F"encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}." A__ = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" A__ = prefix + resnet_block A__ = re_encoder_block_resnet.sub(_lowerCamelCase , _lowerCamelCase ) elif re_encoder_block_proj_out.fullmatch(_lowerCamelCase ): A__ = re_encoder_block_proj_out.match(_lowerCamelCase ) A__ = regex_match.groups() A__ = F"encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}" A__ = re_encoder_block_proj_out.sub(_lowerCamelCase , _lowerCamelCase ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_lowerCamelCase ): A__ = re_decoder_block_conv_out.match(_lowerCamelCase ) A__ = regex_match.groups() A__ = int(groups[2] ) * 2 + int(groups[3] ) - 2 A__ = F"decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}" A__ = re_decoder_block_conv_out.sub(_lowerCamelCase , _lowerCamelCase ) elif re_decoder_block_resnet.fullmatch(_lowerCamelCase ): A__ = re_decoder_block_resnet.match(_lowerCamelCase ) A__ = regex_match.groups() A__ = int(groups[2] ) * 2 + int(groups[3] ) - 2 A__ = {"1": 1, "3": 2}[groups[-2]] A__ = F"decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}." A__ = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" A__ = prefix + resnet_block A__ = re_decoder_block_resnet.sub(_lowerCamelCase , _lowerCamelCase ) elif re_decoder_block_proj_in.fullmatch(_lowerCamelCase ): A__ = re_decoder_block_proj_in.match(_lowerCamelCase ) A__ = regex_match.groups() A__ = F"decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}" A__ = re_decoder_block_proj_in.sub(_lowerCamelCase , _lowerCamelCase ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_lowerCamelCase ): A__ = re_prior_cond_conv_out.match(_lowerCamelCase ) A__ = regex_match.groups() A__ = int(groups[1] ) * 2 + int(groups[2] ) - 2 A__ = F"conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}" A__ = re_prior_cond_conv_out.sub(_lowerCamelCase , _lowerCamelCase ) elif re_prior_cond_resnet.fullmatch(_lowerCamelCase ): A__ = re_prior_cond_resnet.match(_lowerCamelCase ) A__ = regex_match.groups() A__ = int(groups[1] ) * 2 + int(groups[2] ) - 2 A__ = {"1": 1, "3": 2}[groups[-2]] A__ = F"conditioner_blocks.upsampler.upsample_block.{block_index}." A__ = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" A__ = prefix + resnet_block A__ = re_prior_cond_resnet.sub(_lowerCamelCase , _lowerCamelCase ) elif re_prior_cond_proj_in.fullmatch(_lowerCamelCase ): A__ = re_prior_cond_proj_in.match(_lowerCamelCase ) A__ = regex_match.groups() A__ = F"conditioner_blocks.upsampler.proj_in.{groups[-1]}" A__ = re_prior_cond_proj_in.sub(_lowerCamelCase , _lowerCamelCase ) # keep original key else: A__ = original_key A__ = replace_key(_lowerCamelCase ) if F"{key_prefix}.{key}" not in model_state_dict or key is None: print(F"failed converting {original_key} to {key}, does not match" ) # handle missmatched shape elif value.shape != model_state_dict[F"{key_prefix}.{key}"].shape: A__ = model_state_dict[F"{key_prefix}.{key}"] print(F"{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match" ) A__ = original_key A__ = original_key A__ = value return new_dict @torch.no_grad() def UpperCamelCase ( _lowerCamelCase : str=None , _lowerCamelCase : Dict=None ): for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F"{pytorch_dump_folder_path}/{file.split('/' )[-1]}" ): A__ = requests.get(F"{PREFIX}{file}" , allow_redirects=_lowerCamelCase ) os.makedirs(F"{pytorch_dump_folder_path}/" , exist_ok=_lowerCamelCase ) open(F"{pytorch_dump_folder_path}/{file.split('/' )[-1]}" , "wb" ).write(r.content ) A__ = MODEL_MAPPING[model_name.split("/" )[-1]] A__ = JukeboxConfig.from_pretrained(_lowerCamelCase ) A__ = JukeboxModel(_lowerCamelCase ) A__ = [] A__ = {} for i, dict_name in enumerate(_lowerCamelCase ): A__ = torch.load(F"{pytorch_dump_folder_path}/{dict_name.split('/' )[-1]}" )["model"] A__ = {} for k in old_dic.keys(): if k.endswith(".b" ): A__ = old_dic[k] elif k.endswith(".w" ): A__ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: A__ = old_dic[k] else: A__ = old_dic[k] A__ = "vqvae" if i == 0 else F"priors.{3 - i}" A__ = fix_jukebox_keys(_lowerCamelCase , model.state_dict() , _lowerCamelCase , _lowerCamelCase ) weight_dict.append(_lowerCamelCase ) A__ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_lowerCamelCase ) for i in range(len(_lowerCamelCase ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_lowerCamelCase ).mkdir(exist_ok=_lowerCamelCase ) with open(F"{pytorch_dump_folder_path}/mapping.json" , "w" ) as txtfile: json.dump(_lowerCamelCase , _lowerCamelCase ) print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_lowerCamelCase ) return weight_dict if __name__ == "__main__": __lowerCAmelCase : Dict =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="jukebox-5b-lyrics", type=str, help="Name of the model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default="jukebox-5b-lyrics-converted", type=str, help="Path to the output PyTorch model directory.", ) __lowerCAmelCase : int =parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
440
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): a : Dict = StableDiffusionInpaintPipeline a : Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS a : List[Any] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS a : Optional[Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess a : List[str] = frozenset([] ) def _snake_case ( self : Optional[Any] ) ->Optional[int]: '''simple docstring''' torch.manual_seed(0 ) _UpperCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__UpperCamelCase , ) _UpperCAmelCase = PNDMScheduler(skip_prk_steps=__UpperCamelCase ) torch.manual_seed(0 ) _UpperCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=1_28 , ) torch.manual_seed(0 ) _UpperCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="""gelu""" , projection_dim=5_12 , ) _UpperCAmelCase = CLIPTextModel(__UpperCamelCase ) _UpperCAmelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _UpperCAmelCase = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _snake_case ( self : Tuple , __UpperCamelCase : List[Any] , __UpperCamelCase : Optional[int]=0 ) ->Union[str, Any]: '''simple docstring''' _UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(__UpperCamelCase ) ).to(__UpperCamelCase ) _UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] _UpperCAmelCase = Image.fromarray(np.uinta(__UpperCamelCase ) ).convert("""RGB""" ).resize((64, 64) ) _UpperCAmelCase = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__UpperCamelCase ).startswith("""mps""" ): _UpperCAmelCase = torch.manual_seed(__UpperCamelCase ) else: _UpperCAmelCase = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase ) _UpperCAmelCase = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _snake_case ( self : List[str] ) ->int: '''simple docstring''' _UpperCAmelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = StableDiffusionInpaintPipeline(**__UpperCamelCase ) _UpperCAmelCase = sd_pipe.to(__UpperCamelCase ) sd_pipe.set_progress_bar_config(disable=__UpperCamelCase ) _UpperCAmelCase = self.get_dummy_inputs(__UpperCamelCase ) _UpperCAmelCase = sd_pipe(**__UpperCamelCase ).images _UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCAmelCase = np.array([0.4_7_2_7, 0.5_7_3_5, 0.3_9_4_1, 0.5_4_4_6, 0.5_9_2_6, 0.4_3_9_4, 0.5_0_6_2, 0.4_6_5_4, 0.4_4_7_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _snake_case ( self : str ) ->List[Any]: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): def _snake_case ( self : Tuple ) ->Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self : Tuple ) ->Dict: '''simple docstring''' _UpperCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) _UpperCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) _UpperCAmelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) _UpperCAmelCase = """stabilityai/stable-diffusion-2-inpainting""" _UpperCAmelCase = StableDiffusionInpaintPipeline.from_pretrained(__UpperCamelCase , safety_checker=__UpperCamelCase ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) pipe.enable_attention_slicing() _UpperCAmelCase = """Face of a yellow cat, high resolution, sitting on a park bench""" _UpperCAmelCase = torch.manual_seed(0 ) _UpperCAmelCase = pipe( prompt=__UpperCamelCase , image=__UpperCamelCase , mask_image=__UpperCamelCase , generator=__UpperCamelCase , output_type="""np""" , ) _UpperCAmelCase = output.images[0] assert image.shape == (5_12, 5_12, 3) assert np.abs(expected_image - image ).max() < 9e-3 def _snake_case ( self : List[Any] ) ->List[Any]: '''simple docstring''' _UpperCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) _UpperCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) _UpperCAmelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) _UpperCAmelCase = """stabilityai/stable-diffusion-2-inpainting""" _UpperCAmelCase = StableDiffusionInpaintPipeline.from_pretrained( __UpperCamelCase , torch_dtype=torch.floataa , safety_checker=__UpperCamelCase , ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) pipe.enable_attention_slicing() _UpperCAmelCase = """Face of a yellow cat, high resolution, sitting on a park bench""" _UpperCAmelCase = torch.manual_seed(0 ) _UpperCAmelCase = pipe( prompt=__UpperCamelCase , image=__UpperCamelCase , mask_image=__UpperCamelCase , generator=__UpperCamelCase , output_type="""np""" , ) _UpperCAmelCase = output.images[0] assert image.shape == (5_12, 5_12, 3) assert np.abs(expected_image - image ).max() < 5e-1 def _snake_case ( self : str ) ->Any: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _UpperCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) _UpperCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) _UpperCAmelCase = """stabilityai/stable-diffusion-2-inpainting""" _UpperCAmelCase = PNDMScheduler.from_pretrained(__UpperCamelCase , subfolder="""scheduler""" ) _UpperCAmelCase = StableDiffusionInpaintPipeline.from_pretrained( __UpperCamelCase , safety_checker=__UpperCamelCase , scheduler=__UpperCamelCase , torch_dtype=torch.floataa , ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _UpperCAmelCase = """Face of a yellow cat, high resolution, sitting on a park bench""" _UpperCAmelCase = torch.manual_seed(0 ) _UpperCAmelCase = pipe( prompt=__UpperCamelCase , image=__UpperCamelCase , mask_image=__UpperCamelCase , generator=__UpperCamelCase , num_inference_steps=2 , output_type="""np""" , ) _UpperCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.6_5 * 10**9
19
"""simple docstring""" import argparse import os import re import packaging.version a : str = '''examples/''' a : List[str] = { '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''), '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } a : Tuple = { '''init''': '''src/diffusers/__init__.py''', '''setup''': '''setup.py''', } a : List[str] = '''README.md''' def _UpperCamelCase ( _A , _A , _A ) -> Dict: """simple docstring""" with open(_A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: _UpperCAmelCase = f.read() _UpperCAmelCase ,_UpperCAmelCase = REPLACE_PATTERNS[pattern] _UpperCAmelCase = replace.replace("""VERSION""" , _A ) _UpperCAmelCase = re_pattern.sub(_A , _A ) with open(_A , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(_A ) def _UpperCamelCase ( _A ) -> Union[str, Any]: """simple docstring""" for folder, directories, fnames in os.walk(_A ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(_A , _A ) , _A , pattern="""examples""" ) def _UpperCamelCase ( _A , _A=False ) -> int: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_A , _A , _A ) if not patch: update_version_in_examples(_A ) def _UpperCamelCase ( ) -> Any: """simple docstring""" _UpperCAmelCase = """🤗 Transformers currently provides the following architectures""" _UpperCAmelCase = """1. Want to contribute a new model?""" with open(_A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: _UpperCAmelCase = f.readlines() # Find the start of the list. _UpperCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 _UpperCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): _UpperCAmelCase = lines[index].replace( """https://huggingface.co/docs/diffusers/main/model_doc""" , """https://huggingface.co/docs/diffusers/model_doc""" , ) index += 1 with open(_A , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(_A ) def _UpperCamelCase ( ) -> Optional[int]: """simple docstring""" with open(REPLACE_FILES["""init"""] , """r""" ) as f: _UpperCAmelCase = f.read() _UpperCAmelCase = REPLACE_PATTERNS["""init"""][0].search(_A ).groups()[0] return packaging.version.parse(_A ) def _UpperCamelCase ( _A=False ) -> List[Any]: """simple docstring""" _UpperCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: _UpperCAmelCase = default_version.base_version elif patch: _UpperCAmelCase = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: _UpperCAmelCase = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. _UpperCAmelCase = input(F"""Which version are you releasing? [{default_version}]""" ) if len(_A ) == 0: _UpperCAmelCase = default_version print(F"""Updating version to {version}.""" ) global_version_update(_A , patch=_A ) def _UpperCamelCase ( ) -> List[Any]: """simple docstring""" _UpperCAmelCase = get_version() _UpperCAmelCase = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" _UpperCAmelCase = current_version.base_version # Check with the user we got that right. _UpperCAmelCase = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(_A ) == 0: _UpperCAmelCase = dev_version print(F"""Updating version to {version}.""" ) global_version_update(_A ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": a : Dict = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') a : Tuple = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
19
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 lowerCamelCase ( lowerCamelCase : Tuple , lowerCamelCase : Any): if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer A_ : Dict = flax_key_tuple[:-1] + ("""weight""",) A_ : Optional[int] = torch.permute(_UpperCAmelCase , (0, 2, 1)) elif flax_key_tuple[-1] == "kernel" and ".".join(_UpperCAmelCase): # linear layer A_ : Any = flax_key_tuple[:-1] + ("""weight""",) A_ : int = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: A_ : List[Any] = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def lowerCamelCase ( lowerCamelCase : int , lowerCamelCase : List[str] , lowerCamelCase : List[Any]): if "metadata" in layer: A_ : str = layer.split("""metadata""") A_ : List[str] = """""".join(split_layer[0])[:-1] A_ : List[str] = [tuple(("""metadata""" + split_layer[1]).split("""/"""))] elif "kvstore" in layer: A_ : List[Any] = layer.split("""kvstore""") A_ : Dict = """""".join(split_layer[0])[:-1] A_ : Dict = [tuple(("""kvstore""" + split_layer[1]).split("""/"""))] else: A_ : Dict = layer.split("""/""") A_ : List[str] = """/""".join(split_layer[:-1]) A_ : List[Any] = (split_layer[-1],) if "kvstore/path" in layer: A_ : str = F'{switch_checkpoint_path}/{checkpoint_info[layer]}' elif "kvstore/driver" in layer: A_ : Union[str, Any] = """file""" else: A_ : str = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def lowerCamelCase ( lowerCamelCase : int , lowerCamelCase : List[str]): A_ : Optional[int] = rename_keys(_UpperCAmelCase) A_ : int = {} for k, v in current_block.items(): A_ : Dict = v A_ : Any = new_current_block torch.save(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase ( lowerCamelCase : Tuple , lowerCamelCase : Any , lowerCamelCase : int , lowerCamelCase : Any , lowerCamelCase : str = WEIGHTS_NAME): A_ : str = convert_file_size_to_int(_UpperCAmelCase) A_ : Tuple = [] A_ : List[Any] = {} A_ : Union[str, Any] = 0 A_ : Dict = 0 os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""") as fp: A_ : Union[str, Any] = serialization.msgpack_restore(fp.read())["""optimizer"""]["""target"""] A_ : Union[str, Any] = flatten_dict(_UpperCAmelCase , sep="""/""") A_ : int = {} for layer in checkpoint_info.keys(): A_ , A_ , A_ : List[str] = get_key_and_tensorstore_dict( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if curr_real_layer_name in all_layers: A_ : Dict = content else: A_ : List[str] = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file A_ : int = ts.open(unflatten_dict(all_layers[key])).result().read().result() A_ : List[Any] = torch.tensor(_UpperCAmelCase) A_ : Optional[int] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype) # use the renaming pattern from the small conversion scripts A_ , A_ : Any = rename_base_flax_keys(tuple(key.split("""/""")) , _UpperCAmelCase) A_ : Optional[int] = """/""".join(_UpperCAmelCase) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: A_ : Dict = os.path.join( _UpperCAmelCase , weights_name.replace(""".bin""" , F'-{len(_UpperCAmelCase)+1:05d}-of-???.bin')) rename_and_save_block(_UpperCAmelCase , _UpperCAmelCase) sharded_state_dicts.append(current_block.keys()) del current_block A_ : Optional[Any] = {} A_ : List[Any] = 0 A_ : Tuple = raw_weights.to(getattr(_UpperCAmelCase , _UpperCAmelCase)) current_block_size += weight_size total_size += weight_size # Add the last block A_ : int = os.path.join(_UpperCAmelCase , weights_name.replace(""".bin""" , F'-{len(_UpperCAmelCase)+1:05d}-of-???.bin')) rename_and_save_block(_UpperCAmelCase , _UpperCAmelCase) sharded_state_dicts.append(current_block.keys()) # If we only have one shard, we return it if len(_UpperCAmelCase) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index A_ : Any = {} A_ : Tuple = {} for idx, shard in enumerate(_UpperCAmelCase): A_ : List[Any] = weights_name.replace( """.bin""" , F'-{idx+1:05d}-of-{len(_UpperCAmelCase):05d}.bin') # len(sharded_state_dicts):05d} A_ : List[Any] = os.path.join(_UpperCAmelCase , weights_name.replace(""".bin""" , F'-{idx+1:05d}-of-???.bin')) os.rename(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) A_ : Dict = shard for key in shard: A_ : str = shard_file # Add the metadata A_ : Optional[int] = {"""total_size""": total_size} A_ : Union[str, Any] = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(_UpperCAmelCase , _UpperCAmelCase) , """w""" , encoding="""utf-8""") as f: A_ : Any = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + """\n""" f.write(_UpperCAmelCase) return metadata, index if __name__ == "__main__": __magic_name__ = 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.', ) __magic_name__ = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def lowerCamelCase ( ): from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer A_ : List[str] = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""") config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""") A_ : List[str] = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""") A_ : List[str] = TaTokenizer.from_pretrained("""t5-small""") A_ : str = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" A_ : str = tokenizer(_UpperCAmelCase , return_tensors="""pt""").input_ids A_ : str = model.generate(_UpperCAmelCase , decoder_start_token_id=0) print(tokenizer.decode(out[0]))
665
'''simple docstring''' import math def a ( _UpperCAmelCase ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def a ( _UpperCAmelCase = 1_0_0_0_1 ) -> int: """simple docstring""" try: a_ = int(_UpperCAmelCase ) except (TypeError, ValueError): raise TypeError('Parameter nth must be int or castable to int.' ) from None if nth <= 0: raise ValueError('Parameter nth must be greater than or equal to one.' ) a_ = [] a_ = 2 while len(_UpperCAmelCase ) < nth: if is_prime(_UpperCAmelCase ): primes.append(_UpperCAmelCase ) num += 1 else: num += 1 return primes[len(_UpperCAmelCase ) - 1] if __name__ == "__main__": print(f'''{solution() = }''')
697
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'microsoft/deberta-v2-xlarge': 'https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json', 'microsoft/deberta-v2-xxlarge': 'https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json', 'microsoft/deberta-v2-xlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json' ), 'microsoft/deberta-v2-xxlarge-mnli': ( 'https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json' ), } class __A ( lowerCamelCase__ ): """simple docstring""" UpperCAmelCase__ = """deberta-v2""" def __init__( self , a__=12_8100 , a__=1536 , a__=24 , a__=24 , a__=6144 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=0 , a__=0.02 , a__=1e-7 , a__=False , a__=-1 , a__=0 , a__=True , a__=None , a__=0 , a__="gelu" , **a__ , ): """simple docstring""" super().__init__(**a__) _lowerCamelCase : List[str] = hidden_size _lowerCamelCase : Any = num_hidden_layers _lowerCamelCase : Tuple = num_attention_heads _lowerCamelCase : List[Any] = intermediate_size _lowerCamelCase : Dict = hidden_act _lowerCamelCase : List[str] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : str = max_position_embeddings _lowerCamelCase : List[Any] = type_vocab_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Optional[int] = relative_attention _lowerCamelCase : List[str] = max_relative_positions _lowerCamelCase : List[str] = pad_token_id _lowerCamelCase : Tuple = position_biased_input # Backwards compatibility if type(a__) == str: _lowerCamelCase : Union[str, Any] = [x.strip() for x in pos_att_type.lower().split('''|''')] _lowerCamelCase : int = pos_att_type _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : str = layer_norm_eps _lowerCamelCase : Optional[Any] = kwargs.get('''pooler_hidden_size''' , a__) _lowerCamelCase : Any = pooler_dropout _lowerCamelCase : Union[str, Any] = pooler_hidden_act class __A ( lowerCamelCase__ ): """simple docstring""" @property def __snake_case ( self): """simple docstring""" if self.task == "multiple-choice": _lowerCamelCase : int = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _lowerCamelCase : Union[str, Any] = {0: '''batch''', 1: '''sequence'''} if self._config.type_vocab_size > 0: return OrderedDict( [('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis)]) else: return OrderedDict([('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis)]) @property def __snake_case ( self): """simple docstring""" return 12 def __snake_case ( self , a__ , a__ = -1 , a__ = -1 , a__ = -1 , a__ = False , a__ = None , a__ = 3 , a__ = 40 , a__ = 40 , a__ = None , ): """simple docstring""" _lowerCamelCase : Optional[int] = super().generate_dummy_inputs(preprocessor=a__ , framework=a__) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
613
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase = {'configuration_opt': ['OPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OPTConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'OPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'OPTForCausalLM', 'OPTModel', 'OPTPreTrainedModel', 'OPTForSequenceClassification', 'OPTForQuestionAnswering', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['TFOPTForCausalLM', 'TFOPTModel', 'TFOPTPreTrainedModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'FlaxOPTForCausalLM', 'FlaxOPTModel', 'FlaxOPTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
613
1
'''simple docstring''' def _snake_case ( A_ : str , A_ : int ): """simple docstring""" return x if y == 0 else greatest_common_divisor(_A , x % y ) def _snake_case ( A_ : Optional[Any] , A_ : List[str] ): """simple docstring""" return (x * y) // greatest_common_divisor(_A , _A ) def _snake_case ( A_ : Any = 20 ): """simple docstring""" a_ : List[Any] = 1 for i in range(1 , n + 1 ): a_ : str = lcm(_A , _A ) return g if __name__ == "__main__": print(F"""{solution() = }""")
577
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( a_ ): _SCREAMING_SNAKE_CASE = ["""image_processor""", """tokenizer"""] _SCREAMING_SNAKE_CASE = """ChineseCLIPImageProcessor""" _SCREAMING_SNAKE_CASE = ("""BertTokenizer""", """BertTokenizerFast""") def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Tuple=None , **__SCREAMING_SNAKE_CASE : List[Any] ): __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." , __SCREAMING_SNAKE_CASE , ) __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__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __a = self.image_processor def __call__( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Tuple=None , **__SCREAMING_SNAKE_CASE : List[Any] ): if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: __a = self.tokenizer(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if images is not None: __a = self.image_processor(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text is not None and images is not None: __a = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__SCREAMING_SNAKE_CASE ) , tensor_type=__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self : int , *__SCREAMING_SNAKE_CASE : Optional[Any] , **__SCREAMING_SNAKE_CASE : str ): return self.tokenizer.batch_decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self : List[Any] , *__SCREAMING_SNAKE_CASE : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ): return self.tokenizer.decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @property def _UpperCAmelCase ( self : Union[str, Any] ): __a = self.tokenizer.model_input_names __a = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _UpperCAmelCase ( self : Any ): warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , __SCREAMING_SNAKE_CASE , ) return self.image_processor_class
197
0
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class lowerCAmelCase__ ( __magic_name__ ): '''simple docstring''' def __UpperCamelCase ( self ): '''simple docstring''' __A =tempfile.mkdtemp() __A =5 # Realm tok __A =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __A =os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(lowercase__ , exist_ok=lowercase__ ) __A =os.path.join(lowercase__ , 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] ) ) __A =os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(lowercase__ , exist_ok=lowercase__ ) def __UpperCamelCase ( self ): '''simple docstring''' return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def __UpperCamelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __UpperCamelCase ( self ): '''simple docstring''' __A =RealmConfig(num_block_records=self.num_block_records ) return config def __UpperCamelCase ( self ): '''simple docstring''' __A =Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def __UpperCamelCase ( self ): '''simple docstring''' __A =np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=lowercase__ , ) return block_records def __UpperCamelCase ( self ): '''simple docstring''' __A =RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def __UpperCamelCase ( self ): '''simple docstring''' __A =self.get_config() __A =self.get_dummy_retriever() __A =retriever.tokenizer __A =np.array([0, 3] , dtype='''long''' ) __A =tokenizer(['''Test question'''] ).input_ids __A =tokenizer( ['''the fourth'''] , add_special_tokens=lowercase__ , return_token_type_ids=lowercase__ , return_attention_mask=lowercase__ , ).input_ids __A =config.reader_seq_len __A , __A , __A , __A =retriever( lowercase__ , lowercase__ , answer_ids=lowercase__ , max_length=lowercase__ , return_tensors='''np''' ) self.assertEqual(len(lowercase__ ) , 2 ) self.assertEqual(len(lowercase__ ) , 2 ) self.assertEqual(len(lowercase__ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 1_0) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 1_0) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 1_0) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 1_0) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def __UpperCamelCase ( self ): '''simple docstring''' __A =self.get_config() __A =self.get_dummy_retriever() __A =retriever.tokenizer __A =np.array([0, 3, 5] , dtype='''long''' ) __A =tokenizer(['''Test question'''] ).input_ids __A =tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=lowercase__ , return_token_type_ids=lowercase__ , return_attention_mask=lowercase__ , ).input_ids __A =config.reader_seq_len __A , __A , __A , __A =retriever( lowercase__ , lowercase__ , answer_ids=lowercase__ , max_length=lowercase__ , return_tensors='''np''' ) self.assertEqual([False, True, True] , lowercase__ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , lowercase__ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , lowercase__ ) def __UpperCamelCase ( self ): '''simple docstring''' __A =self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path __A =retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: __A =os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) __A =RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
708
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) _lowerCamelCase : Dict = {'''configuration_vit''': ['''VIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTConfig''', '''ViTOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = ['''ViTFeatureExtractor'''] _lowerCamelCase : int = ['''ViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[str] = [ '''VIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ViTForImageClassification''', '''ViTForMaskedImageModeling''', '''ViTModel''', '''ViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Union[str, Any] = [ '''TFViTForImageClassification''', '''TFViTModel''', '''TFViTPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = [ '''FlaxViTForImageClassification''', '''FlaxViTModel''', '''FlaxViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys _lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
516
0
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 snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): return image elif isinstance(_SCREAMING_SNAKE_CASE , PIL.Image.Image ): __lowercase = [image] if isinstance(image[0] , PIL.Image.Image ): __lowercase = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) )[None, :] for i in image] __lowercase = np.concatenate(_SCREAMING_SNAKE_CASE , axis=0 ) __lowercase = np.array(_SCREAMING_SNAKE_CASE ).astype(np.floataa ) / 2_5_5.0 __lowercase = image.transpose(0 , 3 , 1 , 2 ) __lowercase = 2.0 * image - 1.0 __lowercase = torch.from_numpy(_SCREAMING_SNAKE_CASE ) elif isinstance(image[0] , torch.Tensor ): __lowercase = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) return image def snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0.9_9_9_5 ): if not isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ): __lowercase = True __lowercase = va.device __lowercase = va.cpu().numpy() __lowercase = va.cpu().numpy() __lowercase = np.sum(va * va / (np.linalg.norm(_SCREAMING_SNAKE_CASE ) * np.linalg.norm(_SCREAMING_SNAKE_CASE )) ) if np.abs(_SCREAMING_SNAKE_CASE ) > DOT_THRESHOLD: __lowercase = (1 - t) * va + t * va else: __lowercase = np.arccos(_SCREAMING_SNAKE_CASE ) __lowercase = np.sin(_SCREAMING_SNAKE_CASE ) __lowercase = theta_a * t __lowercase = np.sin(_SCREAMING_SNAKE_CASE ) __lowercase = np.sin(theta_a - theta_t ) / sin_theta_a __lowercase = sin_theta_t / sin_theta_a __lowercase = sa * va + sa * va if inputs_are_torch: __lowercase = torch.from_numpy(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) return va def snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowercase = F.normalize(_SCREAMING_SNAKE_CASE , dim=-1 ) __lowercase = F.normalize(_SCREAMING_SNAKE_CASE , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for param in model.parameters(): __lowercase = value class _A ( _lowercase ): '''simple docstring''' def __init__( self : int , lowerCamelCase : AutoencoderKL , lowerCamelCase : CLIPTextModel , lowerCamelCase : CLIPModel , lowerCamelCase : CLIPTokenizer , lowerCamelCase : UNetaDConditionModel , lowerCamelCase : Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler] , lowerCamelCase : CLIPFeatureExtractor , lowerCamelCase : Dict=None , lowerCamelCase : Optional[int]=None , lowerCamelCase : str=None , ): '''simple docstring''' super().__init__() self.register_modules( vae=lowerCamelCase , text_encoder=lowerCamelCase , clip_model=lowerCamelCase , tokenizer=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase , feature_extractor=lowerCamelCase , coca_model=lowerCamelCase , coca_tokenizer=lowerCamelCase , coca_transform=lowerCamelCase , ) __lowercase = ( feature_extractor.size if isinstance(feature_extractor.size , lowerCamelCase ) else feature_extractor.size["shortest_edge"] ) __lowercase = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , lowerCamelCase ) set_requires_grad(self.clip_model , lowerCamelCase ) def _snake_case ( self : Any , lowerCamelCase : Optional[Union[str, int]] = "auto" ): '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __lowercase = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(lowerCamelCase ) def _snake_case ( self : List[str] ): '''simple docstring''' self.enable_attention_slicing(lowerCamelCase ) def _snake_case ( self : List[str] ): '''simple docstring''' set_requires_grad(self.vae , lowerCamelCase ) def _snake_case ( self : List[Any] ): '''simple docstring''' set_requires_grad(self.vae , lowerCamelCase ) def _snake_case ( self : Tuple ): '''simple docstring''' set_requires_grad(self.unet , lowerCamelCase ) def _snake_case ( self : str ): '''simple docstring''' set_requires_grad(self.unet , lowerCamelCase ) def _snake_case ( self : str , lowerCamelCase : List[Any] , lowerCamelCase : Any , lowerCamelCase : Optional[int] ): '''simple docstring''' __lowercase = min(int(num_inference_steps * strength ) , lowerCamelCase ) __lowercase = max(num_inference_steps - init_timestep , 0 ) __lowercase = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def _snake_case ( self : List[Any] , lowerCamelCase : int , lowerCamelCase : Optional[Any] , lowerCamelCase : str , lowerCamelCase : List[str] , lowerCamelCase : int , lowerCamelCase : str=None ): '''simple docstring''' if not isinstance(lowerCamelCase , torch.Tensor ): raise ValueError(f"""`image` has to be of type `torch.Tensor` but is {type(lowerCamelCase )}""" ) __lowercase = image.to(device=lowerCamelCase , dtype=lowerCamelCase ) if isinstance(lowerCamelCase , lowerCamelCase ): __lowercase = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(lowerCamelCase ) ] __lowercase = torch.cat(lowerCamelCase , dim=0 ) else: __lowercase = self.vae.encode(lowerCamelCase ).latent_dist.sample(lowerCamelCase ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowercase = 0.1_8215 * init_latents __lowercase = init_latents.repeat_interleave(lowerCamelCase , dim=0 ) __lowercase = randn_tensor(init_latents.shape , generator=lowerCamelCase , device=lowerCamelCase , dtype=lowerCamelCase ) # get latents __lowercase = self.scheduler.add_noise(lowerCamelCase , lowerCamelCase , lowerCamelCase ) __lowercase = init_latents return latents def _snake_case ( self : Union[str, Any] , lowerCamelCase : List[Any] ): '''simple docstring''' __lowercase = self.coca_transform(lowerCamelCase ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): __lowercase = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) __lowercase = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split("<end_of_text>" )[0].replace("<start_of_text>" , "" ).rstrip(" .," ) def _snake_case ( self : Any , lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[Any] ): '''simple docstring''' __lowercase = self.feature_extractor.preprocess(lowerCamelCase ) __lowercase = torch.from_numpy(clip_image_input["pixel_values"][0] ).unsqueeze(0 ).to(self.device ).half() __lowercase = self.clip_model.get_image_features(lowerCamelCase ) __lowercase = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=lowerCamelCase ) __lowercase = image_embeddings_clip.repeat_interleave(lowerCamelCase , dim=0 ) return image_embeddings_clip @torch.enable_grad() def _snake_case ( self : Union[str, Any] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[int] , lowerCamelCase : Any , lowerCamelCase : List[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : Tuple , lowerCamelCase : Tuple , ): '''simple docstring''' __lowercase = latents.detach().requires_grad_() __lowercase = self.scheduler.scale_model_input(lowerCamelCase , lowerCamelCase ) # predict the noise residual __lowercase = self.unet(lowerCamelCase , lowerCamelCase , encoder_hidden_states=lowerCamelCase ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): __lowercase = self.scheduler.alphas_cumprod[timestep] __lowercase = 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 __lowercase = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 __lowercase = torch.sqrt(lowerCamelCase ) __lowercase = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , lowerCamelCase ): __lowercase = self.scheduler.sigmas[index] __lowercase = 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 __lowercase = 1 / 0.1_8215 * sample __lowercase = self.vae.decode(lowerCamelCase ).sample __lowercase = (image / 2 + 0.5).clamp(0 , 1 ) __lowercase = transforms.Resize(self.feature_extractor_size )(lowerCamelCase ) __lowercase = self.normalize(lowerCamelCase ).to(latents.dtype ) __lowercase = self.clip_model.get_image_features(lowerCamelCase ) __lowercase = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=lowerCamelCase ) __lowercase = spherical_dist_loss(lowerCamelCase , lowerCamelCase ).mean() * clip_guidance_scale __lowercase = -torch.autograd.grad(lowerCamelCase , lowerCamelCase )[0] if isinstance(self.scheduler , lowerCamelCase ): __lowercase = latents.detach() + grads * (sigma**2) __lowercase = noise_pred_original else: __lowercase = noise_pred_original - torch.sqrt(lowerCamelCase ) * grads return noise_pred, latents @torch.no_grad() def __call__( self : List[str] , lowerCamelCase : Union[torch.FloatTensor, PIL.Image.Image] , lowerCamelCase : Union[torch.FloatTensor, PIL.Image.Image] , lowerCamelCase : Optional[str] = None , lowerCamelCase : Optional[str] = None , lowerCamelCase : Optional[int] = 512 , lowerCamelCase : Optional[int] = 512 , lowerCamelCase : float = 0.6 , lowerCamelCase : Optional[int] = 50 , lowerCamelCase : Optional[float] = 7.5 , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : float = 0.0 , lowerCamelCase : Optional[float] = 100 , lowerCamelCase : Optional[torch.Generator] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , lowerCamelCase : float = 0.8 , lowerCamelCase : float = 0.1 , lowerCamelCase : float = 0.1 , ): '''simple docstring''' if isinstance(lowerCamelCase , lowerCamelCase ) and len(lowerCamelCase ) != batch_size: raise ValueError(f"""You have passed {batch_size} batch_size, but only {len(lowerCamelCase )} 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(lowerCamelCase , torch.Generator ) and batch_size > 1: __lowercase = [generator] + [None] * (batch_size - 1) __lowercase = [ ("model", self.coca_model is None), ("tokenizer", self.coca_tokenizer is None), ("transform", self.coca_transform is None), ] __lowercase = [x[0] for x in coca_is_none if x[1]] __lowercase = ", ".join(lowerCamelCase ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(lowerCamelCase ): 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.""" ) __lowercase = self.get_image_description(lowerCamelCase ) if style_prompt is None: if len(lowerCamelCase ): 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.""" ) __lowercase = self.get_image_description(lowerCamelCase ) # get prompt text embeddings for content and style __lowercase = self.tokenizer( lowerCamelCase , padding="max_length" , max_length=self.tokenizer.model_max_length , truncation=lowerCamelCase , return_tensors="pt" , ) __lowercase = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] __lowercase = self.tokenizer( lowerCamelCase , padding="max_length" , max_length=self.tokenizer.model_max_length , truncation=lowerCamelCase , return_tensors="pt" , ) __lowercase = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] __lowercase = slerp(lowerCamelCase , lowerCamelCase , lowerCamelCase ) # duplicate text embeddings for each generation per prompt __lowercase = text_embeddings.repeat_interleave(lowerCamelCase , dim=0 ) # set timesteps __lowercase = "offset" in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) __lowercase = {} if accepts_offset: __lowercase = 1 self.scheduler.set_timesteps(lowerCamelCase , **lowerCamelCase ) # 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 ) __lowercase , __lowercase = self.get_timesteps(lowerCamelCase , lowerCamelCase , self.device ) __lowercase = timesteps[:1].repeat(lowerCamelCase ) # Preprocess image __lowercase = preprocess(lowerCamelCase , lowerCamelCase , lowerCamelCase ) __lowercase = self.prepare_latents( lowerCamelCase , lowerCamelCase , lowerCamelCase , text_embeddings.dtype , self.device , lowerCamelCase ) __lowercase = preprocess(lowerCamelCase , lowerCamelCase , lowerCamelCase ) __lowercase = self.prepare_latents( lowerCamelCase , lowerCamelCase , lowerCamelCase , text_embeddings.dtype , self.device , lowerCamelCase ) __lowercase = slerp(lowerCamelCase , lowerCamelCase , lowerCamelCase ) if clip_guidance_scale > 0: __lowercase = self.get_clip_image_embeddings(lowerCamelCase , lowerCamelCase ) __lowercase = self.get_clip_image_embeddings(lowerCamelCase , lowerCamelCase ) __lowercase = slerp( lowerCamelCase , lowerCamelCase , lowerCamelCase ) # 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. __lowercase = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __lowercase = content_text_input.input_ids.shape[-1] __lowercase = self.tokenizer([""] , padding="max_length" , max_length=lowerCamelCase , return_tensors="pt" ) __lowercase = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt __lowercase = uncond_embeddings.repeat_interleave(lowerCamelCase , 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 __lowercase = 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`. __lowercase = (batch_size, self.unet.config.in_channels, height // 8, width // 8) __lowercase = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps __lowercase = torch.randn(lowerCamelCase , generator=lowerCamelCase , device="cpu" , dtype=lowerCamelCase ).to( self.device ) else: __lowercase = torch.randn(lowerCamelCase , generator=lowerCamelCase , device=self.device , dtype=lowerCamelCase ) else: if latents.shape != latents_shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) __lowercase = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __lowercase = 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] __lowercase = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __lowercase = {} if accepts_eta: __lowercase = eta # check if the scheduler accepts generator __lowercase = "generator" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: __lowercase = generator with self.progress_bar(total=lowerCamelCase ): for i, t in enumerate(lowerCamelCase ): # expand the latents if we are doing classifier free guidance __lowercase = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __lowercase = self.scheduler.scale_model_input(lowerCamelCase , lowerCamelCase ) # predict the noise residual __lowercase = self.unet(lowerCamelCase , lowerCamelCase , encoder_hidden_states=lowerCamelCase ).sample # perform classifier free guidance if do_classifier_free_guidance: __lowercase , __lowercase = noise_pred.chunk(2 ) __lowercase = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: __lowercase = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) __lowercase , __lowercase = self.cond_fn( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ) # compute the previous noisy sample x_t -> x_t-1 __lowercase = self.scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , **lowerCamelCase ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowercase = 1 / 0.1_8215 * latents __lowercase = self.vae.decode(lowerCamelCase ).sample __lowercase = (image / 2 + 0.5).clamp(0 , 1 ) __lowercase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __lowercase = self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=lowerCamelCase , nsfw_content_detected=lowerCamelCase )
402
import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class _A ( _lowercase , unittest.TestCase ): '''simple docstring''' _snake_case : int = RoFormerTokenizer _snake_case : Optional[Any] = RoFormerTokenizerFast _snake_case : int = True _snake_case : Tuple = True def _snake_case ( self : Union[str, Any] ): '''simple docstring''' super().setUp() def _snake_case ( self : Optional[int] , **lowerCamelCase : int ): '''simple docstring''' return self.tokenizer_class.from_pretrained("junnyu/roformer_chinese_base" , **lowerCamelCase ) def _snake_case ( self : List[Any] , **lowerCamelCase : List[str] ): '''simple docstring''' return self.rust_tokenizer_class.from_pretrained("junnyu/roformer_chinese_base" , **lowerCamelCase ) def _snake_case ( self : Dict ): '''simple docstring''' __lowercase = "永和服装饰品有限公司,今天天气非常好" __lowercase = "永和 服装 饰品 有限公司 , 今 天 天 气 非常 好" return input_text, output_text def _snake_case ( self : int ): '''simple docstring''' __lowercase = self.get_tokenizer() __lowercase , __lowercase = self.get_chinese_input_output_texts() __lowercase = tokenizer.tokenize(lowerCamelCase ) self.assertListEqual(lowerCamelCase , output_text.split() ) __lowercase = tokens + [tokenizer.unk_token] __lowercase = [22_943, 21_332, 34_431, 45_904, 117, 306, 1_231, 1_231, 2_653, 33_994, 1_266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase ) , lowerCamelCase ) def _snake_case ( self : str ): '''simple docstring''' __lowercase = self.get_rust_tokenizer() __lowercase , __lowercase = self.get_chinese_input_output_texts() __lowercase = tokenizer.tokenize(lowerCamelCase ) self.assertListEqual(lowerCamelCase , output_text.split() ) __lowercase = tokens + [tokenizer.unk_token] __lowercase = [22_943, 21_332, 34_431, 45_904, 117, 306, 1_231, 1_231, 2_653, 33_994, 1_266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase ) , lowerCamelCase ) def _snake_case ( self : int ): '''simple docstring''' pass def _snake_case ( self : Union[str, Any] ): '''simple docstring''' pass def _snake_case ( self : str ): '''simple docstring''' pass
402
1
'''simple docstring''' import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def __UpperCAmelCase ( __magic_name__ )-> List[Any]: """simple docstring""" snake_case_ : Optional[int] = [2, 2, 6, 2] if "tiny" in model_name else [2, 2, 18, 2] snake_case_ : List[Any] = True if "large" in model_name or "huge" in model_name else False snake_case_ : List[Any] = True if "large" in model_name or "huge" in model_name else False snake_case_ : int = True if "large" in model_name or "huge" in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: snake_case_ : List[Any] = [3, 3, 3, 3] snake_case_ : Any = [5, 5, 5, 5] elif "fl4" in model_name: snake_case_ : int = [4, 4, 4, 4] snake_case_ : Optional[Any] = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: snake_case_ : str = [3, 3, 3, 3] if "lrf" in model_name: snake_case_ : List[Any] = [3, 3, 3, 3] else: snake_case_ : List[Any] = [2, 2, 2, 2] if "tiny" in model_name: snake_case_ : List[Any] = 96 elif "small" in model_name: snake_case_ : Any = 96 elif "base" in model_name: snake_case_ : str = 128 elif "large" in model_name: snake_case_ : List[Any] = 192 elif "xlarge" in model_name: snake_case_ : int = 256 elif "huge" in model_name: snake_case_ : str = 352 # set label information snake_case_ : int = "huggingface/label-files" if "large" in model_name or "huge" in model_name: snake_case_ : List[Any] = "imagenet-22k-id2label.json" else: snake_case_ : List[str] = "imagenet-1k-id2label.json" snake_case_ : Union[str, Any] = json.load(open(hf_hub_download(__magic_name__ ,__magic_name__ ,repo_type="dataset" ) ,"r" ) ) snake_case_ : str = {int(__magic_name__ ): v for k, v in idalabel.items()} snake_case_ : str = {v: k for k, v in idalabel.items()} snake_case_ : int = FocalNetConfig( embed_dim=__magic_name__ ,depths=__magic_name__ ,focal_levels=__magic_name__ ,focal_windows=__magic_name__ ,use_conv_embed=__magic_name__ ,idalabel=__magic_name__ ,labelaid=__magic_name__ ,use_post_layernorm=__magic_name__ ,use_layerscale=__magic_name__ ,) return config def __UpperCAmelCase ( __magic_name__ )-> List[str]: """simple docstring""" if "patch_embed.proj" in name: snake_case_ : Union[str, Any] = name.replace("patch_embed.proj" ,"embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: snake_case_ : Tuple = name.replace("patch_embed.norm" ,"embeddings.norm" ) if "layers" in name: snake_case_ : Optional[int] = "encoder." + name if "encoder.layers" in name: snake_case_ : Tuple = name.replace("encoder.layers" ,"encoder.stages" ) if "downsample.proj" in name: snake_case_ : Tuple = name.replace("downsample.proj" ,"downsample.projection" ) if "blocks" in name: snake_case_ : int = name.replace("blocks" ,"layers" ) if "modulation.f.weight" in name or "modulation.f.bias" in name: snake_case_ : List[Any] = name.replace("modulation.f" ,"modulation.projection_in" ) if "modulation.h.weight" in name or "modulation.h.bias" in name: snake_case_ : str = name.replace("modulation.h" ,"modulation.projection_context" ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: snake_case_ : int = name.replace("modulation.proj" ,"modulation.projection_out" ) if name == "norm.weight": snake_case_ : Any = "layernorm.weight" if name == "norm.bias": snake_case_ : Any = "layernorm.bias" if "head" in name: snake_case_ : Optional[Any] = name.replace("head" ,"classifier" ) else: snake_case_ : List[str] = "focalnet." + name return name def __UpperCAmelCase ( __magic_name__ ,__magic_name__ ,__magic_name__=False )-> Dict: """simple docstring""" snake_case_ : Tuple = { "focalnet-tiny": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth", "focalnet-tiny-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth", "focalnet-small": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth", "focalnet-small-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth", "focalnet-base": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth", "focalnet-base-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth", "focalnet-large-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth", "focalnet-large-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth", "focalnet-xlarge-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth", "focalnet-xlarge-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth", } # fmt: on snake_case_ : Any = model_name_to_url[model_name] print("Checkpoint URL: " ,__magic_name__ ) snake_case_ : Union[str, Any] = torch.hub.load_state_dict_from_url(__magic_name__ ,map_location="cpu" )["model"] # rename keys for key in state_dict.copy().keys(): snake_case_ : Optional[int] = state_dict.pop(__magic_name__ ) snake_case_ : List[str] = val snake_case_ : str = get_focalnet_config(__magic_name__ ) snake_case_ : List[Any] = FocalNetForImageClassification(__magic_name__ ) model.eval() # load state dict model.load_state_dict(__magic_name__ ) # verify conversion snake_case_ : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg" snake_case_ : Any = BitImageProcessor( do_resize=__magic_name__ ,size={"shortest_edge": 256} ,resample=PILImageResampling.BILINEAR ,do_center_crop=__magic_name__ ,crop_size=224 ,do_normalize=__magic_name__ ,image_mean=__magic_name__ ,image_std=__magic_name__ ,) snake_case_ : Any = Image.open(requests.get(__magic_name__ ,stream=__magic_name__ ).raw ) snake_case_ : Tuple = processor(images=__magic_name__ ,return_tensors="pt" ) snake_case_ : Union[str, Any] = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] ,std=[0.229, 0.224, 0.225] ), ] ) snake_case_ : Optional[Any] = image_transforms(__magic_name__ ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values ,__magic_name__ ,atol=1E-4 ) snake_case_ : int = model(**__magic_name__ ) snake_case_ : Dict = outputs.logits.argmax(-1 ).item() print("Predicted class:" ,model.config.idalabel[predicted_class_idx] ) print("First values of logits:" ,outputs.logits[0, :3] ) if model_name == "focalnet-tiny": snake_case_ : Tuple = torch.tensor([0.2_166, -0.4_368, 0.2_191] ) elif model_name == "focalnet-tiny-lrf": snake_case_ : Optional[Any] = torch.tensor([1.1_669, 0.0_125, -0.1_695] ) elif model_name == "focalnet-small": snake_case_ : List[Any] = torch.tensor([0.4_917, -0.0_430, 0.1_341] ) elif model_name == "focalnet-small-lrf": snake_case_ : Optional[int] = torch.tensor([-0.2_588, -0.5_342, -0.2_331] ) elif model_name == "focalnet-base": snake_case_ : List[Any] = torch.tensor([-0.1_655, -0.4_090, -0.1_730] ) elif model_name == "focalnet-base-lrf": snake_case_ : List[str] = torch.tensor([0.5_306, -0.0_483, -0.3_928] ) assert torch.allclose(outputs.logits[0, :3] ,__magic_name__ ,atol=1E-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(F'''Saving model and processor of {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(__magic_name__ ) processor.save_pretrained(__magic_name__ ) if push_to_hub: print(F'''Pushing model and processor of {model_name} to the hub...''' ) model.push_to_hub(F'''{model_name}''' ) processor.push_to_hub(F'''{model_name}''' ) if __name__ == "__main__": __lowerCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''focalnet-tiny''', type=str, help='''Name of the FocalNet model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to push the model and processor to the hub.''', ) __lowerCamelCase : List[Any] = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
656
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable __lowerCamelCase : Dict = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : int = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys __lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
656
1
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.linear_k""": """encoder.layers.*.self_attn.linear_k""", """self_attn.linear_v""": """encoder.layers.*.self_attn.linear_v""", """self_attn.linear_q""": """encoder.layers.*.self_attn.linear_q""", """self_attn.pos_bias_u""": """encoder.layers.*.self_attn.pos_bias_u""", """self_attn.pos_bias_v""": """encoder.layers.*.self_attn.pos_bias_v""", """self_attn.linear_out""": """encoder.layers.*.self_attn.linear_out""", """self_attn.linear_pos""": """encoder.layers.*.self_attn.linear_pos""", """self_attn.rotary_emb""": """encoder.embed_positions""", """self_attn_layer_norm""": """encoder.layers.*.self_attn_layer_norm""", """conv_module.pointwise_conv1""": """encoder.layers.*.conv_module.pointwise_conv1""", """conv_module.pointwise_conv2""": """encoder.layers.*.conv_module.pointwise_conv2""", """conv_module.depthwise_conv""": """encoder.layers.*.conv_module.depthwise_conv""", """conv_module.batch_norm""": """encoder.layers.*.conv_module.batch_norm""", """conv_module.layer_norm""": """encoder.layers.*.conv_module.layer_norm""", """ffn1.w_1""": """encoder.layers.*.ffn1.intermediate_dense""", """ffn1.w_2""": """encoder.layers.*.ffn1.output_dense""", """ffn1.layer_norm""": """encoder.layers.*.ffn1_layer_norm""", """ffn2.w_1""": """encoder.layers.*.ffn2.intermediate_dense""", """ffn2.w_2""": """encoder.layers.*.ffn2.output_dense""", """ffn2.layer_norm""": """encoder.layers.*.ffn2_layer_norm""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } __lowerCAmelCase = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def UpperCAmelCase_ (__a : int , __a : int , __a : Dict , __a : List[str] , __a : List[Any] ): """simple docstring""" for attribute in key.split('.' ): _a : List[str] = getattr(__a , __a ) if weight_type is not None: _a : Any = getattr(__a , __a ).shape else: _a : Optional[int] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": _a : Dict = value elif weight_type == "weight_g": _a : Tuple = value elif weight_type == "weight_v": _a : List[str] = value elif weight_type == "bias": _a : List[str] = value elif weight_type == "running_mean": _a : Any = value elif weight_type == "running_var": _a : Optional[int] = value elif weight_type == "num_batches_tracked": _a : int = value elif weight_type == "inv_freq": _a : Dict = value else: _a : int = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def UpperCAmelCase_ (__a : int , __a : Dict , __a : Optional[Any] ): """simple docstring""" _a : Tuple = [] _a : Optional[Any] = fairseq_model.state_dict() _a : Optional[int] = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): _a : Optional[int] = False if "conv_layers" in name: load_conv_layer( __a , __a , __a , __a , hf_model.config.feat_extract_norm == 'group' , ) _a : Any = True else: for key, mapped_key in MAPPING.items(): _a : List[Any] = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: _a : Union[str, Any] = True if "*" in mapped_key: _a : int = name.split(__a )[0].split('.' )[-2] _a : Union[str, Any] = mapped_key.replace('*' , __a ) if "pos_bias_u" in name: _a : Tuple = None elif "pos_bias_v" in name: _a : Optional[Any] = None elif "weight_g" in name: _a : Tuple = 'weight_g' elif "weight_v" in name: _a : List[str] = 'weight_v' elif "bias" in name: _a : List[str] = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj _a : Union[str, Any] = 'weight' elif "running_mean" in name: _a : List[str] = 'running_mean' elif "inv_freq" in name: _a : List[str] = 'inv_freq' elif "running_var" in name: _a : Optional[Any] = 'running_var' elif "num_batches_tracked" in name: _a : List[Any] = 'num_batches_tracked' else: _a : Any = None set_recursively(__a , __a , __a , __a , __a ) continue if not is_used: unused_weights.append(__a ) logger.warning(f"""Unused weights: {unused_weights}""" ) def UpperCAmelCase_ (__a : str , __a : Optional[Any] , __a : Tuple , __a : Any , __a : Optional[int] ): """simple docstring""" _a : int = full_name.split('conv_layers.' )[-1] _a : Union[str, Any] = name.split('.' ) _a : List[str] = int(items[0] ) _a : str = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _a : Tuple = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _a : int = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) _a : Optional[Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) _a : Tuple = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__a ) @torch.no_grad() def UpperCAmelCase_ (__a : Tuple , __a : Optional[Any] , __a : List[Any]=None , __a : int=None , __a : Optional[int]=True ): """simple docstring""" if config_path is not None: _a : Union[str, Any] = WavaVecaConformerConfig.from_pretrained(__a , hidden_act='swish' ) else: _a : Dict = WavaVecaConformerConfig() if "rope" in checkpoint_path: _a : List[Any] = 'rotary' if is_finetuned: if dict_path: _a : Union[str, Any] = Dictionary.load(__a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _a : Optional[int] = target_dict.pad_index _a : Optional[Any] = target_dict.bos_index _a : List[str] = target_dict.eos_index _a : Tuple = len(target_dict.symbols ) _a : Union[str, Any] = os.path.join(__a , 'vocab.json' ) if not os.path.isdir(__a ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(__a ) ) return os.makedirs(__a , exist_ok=__a ) _a : str = target_dict.indices # fairseq has the <pad> and <s> switched _a : Optional[int] = 0 _a : Dict = 1 with open(__a , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(__a , __a ) _a : Optional[int] = WavaVecaCTCTokenizer( __a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=__a , ) _a : Tuple = True if config.feat_extract_norm == 'layer' else False _a : List[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=__a , return_attention_mask=__a , ) _a : Tuple = WavaVecaProcessor(feature_extractor=__a , tokenizer=__a ) processor.save_pretrained(__a ) _a : Tuple = WavaVecaConformerForCTC(__a ) else: _a : int = WavaVecaConformerForPreTraining(__a ) if is_finetuned: _a, _a, _a : Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: _a : Optional[int] = argparse.Namespace(task='audio_pretraining' ) _a : Dict = fairseq.tasks.setup_task(__a ) _a, _a, _a : List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=__a ) _a : str = model[0].eval() recursively_load_weights(__a , __a , not is_finetuned ) hf_wavavec.save_pretrained(__a ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) __lowerCAmelCase = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
229
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = StableDiffusionLDMaDPipeline __UpperCAmelCase : Optional[int] = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase : str = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase : Any = TEXT_TO_IMAGE_IMAGE_PARAMS def __lowercase ( self : str ): '''simple docstring''' torch.manual_seed(0 ) _a : Optional[int] = 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 : Optional[int] = DDIMScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule='scaled_linear' ,clip_sample=_a ,set_alpha_to_one=_a ,) torch.manual_seed(0 ) _a : Tuple = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=6 ,out_channels=6 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,) torch.manual_seed(0 ) _a : List[str] = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,) _a : List[str] = CLIPTextModel(_a ) _a : List[str] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _a : List[Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase ( self : List[str] ,_a : Optional[Any] ,_a : Tuple=0 ): '''simple docstring''' if str(_a ).startswith('mps' ): _a : Optional[Any] = torch.manual_seed(_a ) else: _a : Dict = torch.Generator(device=_a ).manual_seed(_a ) _a : Tuple = { '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 __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator _a : Optional[Any] = self.get_dummy_components() _a : int = StableDiffusionLDMaDPipeline(**_a ) _a : str = ldmad_pipe.to(_a ) ldmad_pipe.set_progress_bar_config(disable=_a ) _a : Optional[int] = self.get_dummy_inputs(_a ) _a : Union[str, Any] = ldmad_pipe(**_a ) _a, _a : str = output.rgb, output.depth _a : int = rgb[0, -3:, -3:, -1] _a : List[str] = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) _a : Dict = np.array( [0.3733_8176, 0.7_0247, 0.7420_3193, 0.5164_3604, 0.5825_6793, 0.6093_2136, 0.418_1095, 0.4835_5877, 0.4653_5262] ) _a : Union[str, Any] = np.array([103.4_6727, 85.81_2004, 87.84_9236] ) assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1E-2 def __lowercase ( self : int ): '''simple docstring''' _a : Any = self.get_dummy_components() _a : int = StableDiffusionLDMaDPipeline(**_a ) _a : List[Any] = ldmad_pipe.to(_a ) ldmad_pipe.set_progress_bar_config(disable=_a ) _a : Any = self.get_dummy_inputs(_a ) _a : List[str] = 3 * [inputs['prompt']] # forward _a : int = ldmad_pipe(**_a ) _a, _a : Union[str, Any] = output.rgb, output.depth _a : Optional[Any] = rgb_slice_a[0, -3:, -3:, -1] _a : Tuple = depth_slice_a[0, -3:, -1] _a : Tuple = self.get_dummy_inputs(_a ) _a : Tuple = 3 * [inputs.pop('prompt' )] _a : List[Any] = ldmad_pipe.tokenizer( _a ,padding='max_length' ,max_length=ldmad_pipe.tokenizer.model_max_length ,truncation=_a ,return_tensors='pt' ,) _a : Union[str, Any] = text_inputs['input_ids'].to(_a ) _a : List[str] = ldmad_pipe.text_encoder(_a )[0] _a : int = prompt_embeds # forward _a : str = ldmad_pipe(**_a ) _a, _a : str = output.rgb, output.depth _a : Tuple = rgb_slice_a[0, -3:, -3:, -1] _a : Optional[Any] = depth_slice_a[0, -3:, -1] assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1E-4 assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1E-4 def __lowercase ( self : Union[str, Any] ): '''simple docstring''' _a : Tuple = 'cpu' # ensure determinism for the device-dependent torch.Generator _a : Dict = self.get_dummy_components() _a : Dict = PNDMScheduler(skip_prk_steps=_a ) _a : str = StableDiffusionLDMaDPipeline(**_a ) _a : str = ldmad_pipe.to(_a ) ldmad_pipe.set_progress_bar_config(disable=_a ) _a : Union[str, Any] = self.get_dummy_inputs(_a ) _a : List[Any] = 'french fries' _a : Dict = ldmad_pipe(**_a ,negative_prompt=_a ) _a, _a : Any = output.rgb, output.depth _a : Tuple = rgb[0, -3:, -3:, -1] _a : List[Any] = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) _a : str = np.array( [0.3_7044, 0.7181_1503, 0.722_3251, 0.4860_3675, 0.563_8391, 0.636_4948, 0.4283_3704, 0.490_1315, 0.4792_6217] ) _a : Optional[int] = np.array([107.8_4738, 84.6_2802, 89.96_2135] ) assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1E-2 @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Union[str, Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self : Tuple ,_a : Union[str, Any] ,_a : int="cpu" ,_a : Union[str, Any]=torch.floataa ,_a : str=0 ): '''simple docstring''' _a : str = torch.Generator(device=_a ).manual_seed(_a ) _a : List[str] = np.random.RandomState(_a ).standard_normal((1, 4, 64, 64) ) _a : int = torch.from_numpy(_a ).to(device=_a ,dtype=_a ) _a : Union[str, Any] = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Any = StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d' ) _a : Optional[int] = ldmad_pipe.to(_a ) ldmad_pipe.set_progress_bar_config(disable=_a ) _a : Tuple = self.get_inputs(_a ) _a : Tuple = ldmad_pipe(**_a ) _a, _a : Dict = output.rgb, output.depth _a : Union[str, Any] = rgb[0, -3:, -3:, -1].flatten() _a : Union[str, Any] = rgb[0, -3:, -1].flatten() assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512) _a : int = np.array( [0.5380_5465, 0.5670_7305, 0.548_6515, 0.5701_2236, 0.581_4511, 0.5625_3487, 0.5484_3014, 0.5509_2263, 0.645_9706] ) _a : Optional[Any] = np.array( [0.926_3781, 0.667_8672, 0.548_6515, 0.9220_2145, 0.6783_1135, 0.5625_3487, 0.924_1694, 0.755_1478, 0.645_9706] ) assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3E-3 assert np.abs(depth_slice - expected_slice_depth ).max() < 3E-3 @nightly @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self : Tuple ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self : str ,_a : Union[str, Any] ,_a : Any="cpu" ,_a : Union[str, Any]=torch.floataa ,_a : Tuple=0 ): '''simple docstring''' _a : Optional[Any] = torch.Generator(device=_a ).manual_seed(_a ) _a : Optional[Any] = np.random.RandomState(_a ).standard_normal((1, 4, 64, 64) ) _a : Any = torch.from_numpy(_a ).to(device=_a ,dtype=_a ) _a : Dict = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 50, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def __lowercase ( self : int ): '''simple docstring''' _a : str = StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d' ).to(_a ) ldmad_pipe.set_progress_bar_config(disable=_a ) _a : List[Any] = self.get_inputs(_a ) _a : Union[str, Any] = ldmad_pipe(**_a ) _a, _a : Optional[Any] = output.rgb, output.depth _a : Dict = 0.49_5586 _a : Optional[Any] = 0.3379_5515 _a : str = 112.4_8518 _a : Optional[Any] = 98.48_9746 assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3 def __lowercase ( self : int ): '''simple docstring''' _a : List[str] = StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d-4c' ).to(_a ) ldmad_pipe.set_progress_bar_config(disable=_a ) _a : int = self.get_inputs(_a ) _a : Tuple = ldmad_pipe(**_a ) _a, _a : Optional[int] = output.rgb, output.depth _a : Union[str, Any] = 0.419_4127 _a : Tuple = 0.3537_5586 _a : Tuple = 0.563_8502 _a : Tuple = 0.3468_6103 assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512, 1) assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3
229
1
import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 snake_case = { "return_dict": False, "output_hidden_states": True, "output_attentions": True, "torchscript": True, "torch_dtype": "float16", "use_bfloat16": True, "tf_legacy_loss": True, "pruned_heads": {"a": 1}, "tie_word_embeddings": False, "is_decoder": True, "cross_attention_hidden_size": 128, "add_cross_attention": True, "tie_encoder_decoder": True, "max_length": 50, "min_length": 3, "do_sample": True, "early_stopping": True, "num_beams": 3, "num_beam_groups": 3, "diversity_penalty": 0.5, "temperature": 2.0, "top_k": 10, "top_p": 0.7, "typical_p": 0.2, "repetition_penalty": 0.8, "length_penalty": 0.8, "no_repeat_ngram_size": 5, "encoder_no_repeat_ngram_size": 5, "bad_words_ids": [1, 2, 3], "num_return_sequences": 3, "chunk_size_feed_forward": 5, "output_scores": True, "return_dict_in_generate": True, "forced_bos_token_id": 2, "forced_eos_token_id": 3, "remove_invalid_values": True, "architectures": ["BertModel"], "finetuning_task": "translation", "id2label": {0: "label"}, "label2id": {"label": "0"}, "tokenizer_class": "BertTokenizerFast", "prefix": "prefix", "bos_token_id": 6, "pad_token_id": 7, "eos_token_id": 8, "sep_token_id": 9, "decoder_start_token_id": 10, "exponential_decay_length_penalty": (5, 1.01), "suppress_tokens": [0, 1], "begin_suppress_tokens": 2, "task_specific_params": {"translation": "some_params"}, "problem_type": "regression", } @is_staging_test class __A ( unittest.TestCase ): '''simple docstring''' @classmethod def SCREAMING_SNAKE_CASE__ ( cls ): _lowerCAmelCase : Optional[Any] = TOKEN HfFolder.save_token(_snake_case ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls ): try: delete_repo(token=cls._token , repo_id="test-config" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-config-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-config" ) except HTTPError: pass def SCREAMING_SNAKE_CASE__ ( self ): _lowerCAmelCase : Optional[Any] = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("test-config" , use_auth_token=self._token ) _lowerCAmelCase : List[Any] = BertConfig.from_pretrained(F"""{USER}/test-config""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case ) ) # Reset repo delete_repo(token=self._token , repo_id="test-config" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_snake_case , repo_id="test-config" , push_to_hub=_snake_case , use_auth_token=self._token ) _lowerCAmelCase : Union[str, Any] = BertConfig.from_pretrained(F"""{USER}/test-config""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case ) ) def SCREAMING_SNAKE_CASE__ ( self ): _lowerCAmelCase : int = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token ) _lowerCAmelCase : Tuple = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-config-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _snake_case , repo_id="valid_org/test-config-org" , push_to_hub=_snake_case , use_auth_token=self._token ) _lowerCAmelCase : Any = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case ) ) def SCREAMING_SNAKE_CASE__ ( self ): CustomConfig.register_for_auto_class() _lowerCAmelCase : Optional[Any] = CustomConfig(attribute=42 ) config.push_to_hub("test-dynamic-config" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} ) _lowerCAmelCase : Any = AutoConfig.from_pretrained(F"""{USER}/test-dynamic-config""" , trust_remote_code=_snake_case ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , "CustomConfig" ) self.assertEqual(new_config.attribute , 42 ) class __A ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self ): _lowerCAmelCase : Union[str, Any] = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated _lowerCAmelCase : Tuple = c.n_embd + 1 # int _lowerCAmelCase : Dict = c.resid_pdrop + 1.0 # float _lowerCAmelCase : Dict = not c.scale_attn_weights # bool _lowerCAmelCase : int = c.summary_type + "foo" # str c.update_from_string( F"""n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}""" ) self.assertEqual(_snake_case , c.n_embd , "mismatch for key: n_embd" ) self.assertEqual(_snake_case , c.resid_pdrop , "mismatch for key: resid_pdrop" ) self.assertEqual(_snake_case , c.scale_attn_weights , "mismatch for key: scale_attn_weights" ) self.assertEqual(_snake_case , c.summary_type , "mismatch for key: summary_type" ) def SCREAMING_SNAKE_CASE__ ( self ): _lowerCAmelCase : Dict = PretrainedConfig() _lowerCAmelCase : int = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( _snake_case , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] ) _lowerCAmelCase : List[str] = [key for key, value in config_common_kwargs.items() if value == getattr(_snake_case , _snake_case )] if len(_snake_case ) > 0: raise ValueError( "The following keys are set with the default values in" " `test_configuration_common.config_common_kwargs` pick another value for them:" F""" {', '.join(_snake_case )}.""" ) def SCREAMING_SNAKE_CASE__ ( self ): with self.assertRaises(_snake_case ): # config is in subfolder, the following should not work without specifying the subfolder _lowerCAmelCase : Optional[Any] = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" ) _lowerCAmelCase : Optional[Any] = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" ) self.assertIsNotNone(_snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): # A mock response for an HTTP head request to emulate server down _lowerCAmelCase : Tuple = mock.Mock() _lowerCAmelCase : Any = 500 _lowerCAmelCase : Any = {} _lowerCAmelCase : Any = HTTPError _lowerCAmelCase : List[str] = {} # Download this model to make sure it's in the cache. _lowerCAmelCase : Optional[int] = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=_snake_case ) as mock_head: _lowerCAmelCase : Optional[Any] = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE__ ( self ): # This test is for deprecated behavior and can be removed in v5 _lowerCAmelCase : Any = BertConfig.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" ) def SCREAMING_SNAKE_CASE__ ( self ): _lowerCAmelCase : List[str] = AutoConfig.from_pretrained("bert-base-cased" ) _lowerCAmelCase : Tuple = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(_snake_case ) _lowerCAmelCase : Optional[int] = 2 json.dump(configuration.to_dict() , open(os.path.join(_snake_case , "config.4.0.0.json" ) , "w" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 _lowerCAmelCase : int = AutoConfig.from_pretrained(_snake_case ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 _lowerCAmelCase : List[Any] = ["config.42.0.0.json"] _lowerCAmelCase : str = 768 configuration.save_pretrained(_snake_case ) shutil.move(os.path.join(_snake_case , "config.4.0.0.json" ) , os.path.join(_snake_case , "config.42.0.0.json" ) ) _lowerCAmelCase : str = AutoConfig.from_pretrained(_snake_case ) self.assertEqual(new_configuration.hidden_size , 768 ) def SCREAMING_SNAKE_CASE__ ( self ): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. _lowerCAmelCase : List[Any] = "hf-internal-testing/test-two-configs" import transformers as new_transformers _lowerCAmelCase : str = "v4.0.0" _lowerCAmelCase , _lowerCAmelCase : Optional[int] = new_transformers.models.auto.AutoConfig.from_pretrained( _snake_case , return_unused_kwargs=_snake_case ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(_snake_case , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers _lowerCAmelCase : Union[str, Any] = "v3.0.0" _lowerCAmelCase : Any = old_transformers.models.auto.AutoConfig.from_pretrained(_snake_case ) self.assertEqual(old_configuration.hidden_size , 768 )
587
import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging snake_case = logging.get_logger(__name__) snake_case = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all LED models at https://huggingface.co/models?filter=LED snake_case = { "vocab_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", }, "merges_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt", }, "tokenizer_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json", }, } snake_case = { "allenai/led-base-16384": 1_6384, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def UpperCamelCase_ ( ): """simple docstring""" _lowerCAmelCase : Any = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) _lowerCAmelCase : Dict = bs[:] _lowerCAmelCase : str = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCAmelCase__ ) cs.append(2**8 + n ) n += 1 _lowerCAmelCase : int = [chr(lowerCAmelCase__ ) for n in cs] return dict(zip(lowerCAmelCase__ , lowerCAmelCase__ ) ) def UpperCamelCase_ ( lowerCAmelCase__ ): """simple docstring""" _lowerCAmelCase : Optional[Any] = set() _lowerCAmelCase : str = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _lowerCAmelCase : Union[str, Any] = char return pairs class __A ( snake_case__ ): '''simple docstring''' a_ = VOCAB_FILES_NAMES a_ = PRETRAINED_VOCAB_FILES_MAP a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ = ['''input_ids''', '''attention_mask'''] def __init__( self , _snake_case , _snake_case , _snake_case="replace" , _snake_case="<s>" , _snake_case="</s>" , _snake_case="</s>" , _snake_case="<s>" , _snake_case="<unk>" , _snake_case="<pad>" , _snake_case="<mask>" , _snake_case=False , **_snake_case , ): _lowerCAmelCase : Optional[Any] = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else bos_token _lowerCAmelCase : Union[str, Any] = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else eos_token _lowerCAmelCase : Optional[int] = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else sep_token _lowerCAmelCase : str = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else cls_token _lowerCAmelCase : Optional[Any] = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else unk_token _lowerCAmelCase : Union[str, Any] = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else pad_token # Mask token behave like a normal word, i.e. include the space before it _lowerCAmelCase : str = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else mask_token super().__init__( errors=_snake_case , bos_token=_snake_case , eos_token=_snake_case , unk_token=_snake_case , sep_token=_snake_case , cls_token=_snake_case , pad_token=_snake_case , mask_token=_snake_case , add_prefix_space=_snake_case , **_snake_case , ) with open(_snake_case , encoding="utf-8" ) as vocab_handle: _lowerCAmelCase : Tuple = json.load(_snake_case ) _lowerCAmelCase : str = {v: k for k, v in self.encoder.items()} _lowerCAmelCase : Optional[int] = errors # how to handle errors in decoding _lowerCAmelCase : Any = bytes_to_unicode() _lowerCAmelCase : Dict = {v: k for k, v in self.byte_encoder.items()} with open(_snake_case , encoding="utf-8" ) as merges_handle: _lowerCAmelCase : List[str] = merges_handle.read().split("\n" )[1:-1] _lowerCAmelCase : Optional[Any] = [tuple(merge.split() ) for merge in bpe_merges] _lowerCAmelCase : List[Any] = dict(zip(_snake_case , range(len(_snake_case ) ) ) ) _lowerCAmelCase : Tuple = {} _lowerCAmelCase : List[Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions _lowerCAmelCase : Any = re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def SCREAMING_SNAKE_CASE__ ( self ): return len(self.encoder ) def SCREAMING_SNAKE_CASE__ ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE__ ( self , _snake_case ): if token in self.cache: return self.cache[token] _lowerCAmelCase : Optional[int] = tuple(_snake_case ) _lowerCAmelCase : Union[str, Any] = get_pairs(_snake_case ) if not pairs: return token while True: _lowerCAmelCase : Optional[Any] = min(_snake_case , key=lambda _snake_case : self.bpe_ranks.get(_snake_case , float("inf" ) ) ) if bigram not in self.bpe_ranks: break _lowerCAmelCase , _lowerCAmelCase : Tuple = bigram _lowerCAmelCase : int = [] _lowerCAmelCase : List[str] = 0 while i < len(_snake_case ): try: _lowerCAmelCase : Union[str, Any] = word.index(_snake_case , _snake_case ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _lowerCAmelCase : Optional[Any] = j if word[i] == first and i < len(_snake_case ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _lowerCAmelCase : Optional[Any] = tuple(_snake_case ) _lowerCAmelCase : str = new_word if len(_snake_case ) == 1: break else: _lowerCAmelCase : List[str] = get_pairs(_snake_case ) _lowerCAmelCase : Tuple = " ".join(_snake_case ) _lowerCAmelCase : Optional[int] = word return word def SCREAMING_SNAKE_CASE__ ( self , _snake_case ): _lowerCAmelCase : List[str] = [] for token in re.findall(self.pat , _snake_case ): _lowerCAmelCase : List[str] = "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_snake_case ).split(" " ) ) return bpe_tokens def SCREAMING_SNAKE_CASE__ ( self , _snake_case ): return self.encoder.get(_snake_case , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE__ ( self , _snake_case ): return self.decoder.get(_snake_case ) def SCREAMING_SNAKE_CASE__ ( self , _snake_case ): _lowerCAmelCase : str = "".join(_snake_case ) _lowerCAmelCase : int = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case = None ): if not os.path.isdir(_snake_case ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _lowerCAmelCase : List[Any] = os.path.join( _snake_case , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) _lowerCAmelCase : Any = os.path.join( _snake_case , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(_snake_case , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_snake_case , ensure_ascii=_snake_case ) + "\n" ) _lowerCAmelCase : Any = 0 with open(_snake_case , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _snake_case : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" " Please check that the tokenizer is not corrupted!" ) _lowerCAmelCase : Union[str, Any] = token_index writer.write(" ".join(_snake_case ) + "\n" ) index += 1 return vocab_file, merge_file def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _lowerCAmelCase : Union[str, Any] = [self.cls_token_id] _lowerCAmelCase : Any = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case = None , _snake_case = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_snake_case , token_ids_a=_snake_case , already_has_special_tokens=_snake_case ) if token_ids_a is None: return [1] + ([0] * len(_snake_case )) + [1] return [1] + ([0] * len(_snake_case )) + [1, 1] + ([0] * len(_snake_case )) + [1] def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case = None ): _lowerCAmelCase : str = [self.sep_token_id] _lowerCAmelCase : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case=False , **_snake_case ): _lowerCAmelCase : Tuple = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_snake_case ) > 0 and not text[0].isspace()): _lowerCAmelCase : List[str] = " " + text return (text, kwargs) def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case = None , _snake_case = PaddingStrategy.DO_NOT_PAD , _snake_case = None , _snake_case = None , ): _lowerCAmelCase : Union[str, Any] = super()._pad( encoded_inputs=_snake_case , max_length=_snake_case , padding_strategy=_snake_case , pad_to_multiple_of=_snake_case , return_attention_mask=_snake_case , ) # Load from model defaults if return_attention_mask is None: _lowerCAmelCase : Optional[int] = "attention_mask" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: _lowerCAmelCase : int = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. _lowerCAmelCase : Optional[Any] = len(encoded_inputs["global_attention_mask"] ) != len(_snake_case ) if needs_to_be_padded: _lowerCAmelCase : Any = len(_snake_case ) - len(encoded_inputs["global_attention_mask"] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` _lowerCAmelCase : Optional[int] = ( encoded_inputs["global_attention_mask"] + [-1] * difference ) elif self.padding_side == "left": _lowerCAmelCase : List[str] = [-1] * difference + encoded_inputs[ "global_attention_mask" ] else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return encoded_inputs
587
1
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int | None = None , lowerCAmelCase_ : int | None = None ): """simple docstring""" if start is None: lowerCAmelCase__ = 0 if end is None: lowerCAmelCase__ = len(lowerCAmelCase_ ) - 1 if start >= end: return lowerCAmelCase__ = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: lowerCAmelCase__ , lowerCAmelCase__ = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
61
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
1
'''simple docstring''' from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def _lowerCAmelCase( UpperCAmelCase_ : Tuple ) -> Tuple: return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def _lowerCAmelCase( ) -> int: lowerCAmelCase__ = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=UpperCAmelCase_ ) lowerCAmelCase__ = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCAmelCase_ ) EnvironmentCommand.register_subcommand(UpperCAmelCase_ ) TestCommand.register_subcommand(UpperCAmelCase_ ) RunBeamCommand.register_subcommand(UpperCAmelCase_ ) DummyDataCommand.register_subcommand(UpperCAmelCase_ ) # Parse args lowerCAmelCase__ ,lowerCAmelCase__ = parser.parse_known_args() if not hasattr(UpperCAmelCase_ , """func""" ): parser.print_help() exit(1 ) lowerCAmelCase__ = parse_unknown_args(UpperCAmelCase_ ) # Run lowerCAmelCase__ = args.func(UpperCAmelCase_ , **UpperCAmelCase_ ) service.run() if __name__ == "__main__": main()
721
'''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 # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _UpperCamelCase = { """configuration_vivit""": ["""VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VivitConfig"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = ["""VivitImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ """VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """VivitModel""", """VivitPreTrainedModel""", """VivitForVideoClassification""", ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
211
0
import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def UpperCamelCase ( lowercase_ , lowercase_ ) -> Union[str, Any]: '''simple docstring''' assert isinstance(lowercase_ , lowercase_ ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> List[Any]: '''simple docstring''' lowercase__ : Tuple = tmp_path / """cache""" lowercase__ : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowercase__ : Optional[int] = SqlDatasetReader( """dataset""" , """sqlite:///""" + sqlite_path , cache_dir=lowercase_ , keep_in_memory=lowercase_ ).read() _check_sql_dataset(lowercase_ , lowercase_ ) @require_sqlalchemy @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Dict: '''simple docstring''' lowercase__ : Optional[int] = tmp_path / """cache""" lowercase__ : List[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} lowercase__ : Optional[int] = features.copy() if features else default_expected_features lowercase__ : str = ( Features({feature: Value(lowercase_ ) for feature, dtype in features.items()} ) if features is not None else None ) lowercase__ : Tuple = SqlDatasetReader("""dataset""" , """sqlite:///""" + sqlite_path , features=lowercase_ , cache_dir=lowercase_ ).read() _check_sql_dataset(lowercase_ , lowercase_ ) def UpperCamelCase ( lowercase_ ) -> int: '''simple docstring''' with contextlib.closing(sqlitea.connect(lowercase_ ) ) as con: lowercase__ : str = con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ ) -> Optional[int]: '''simple docstring''' lowercase__ : str = tmp_path / """cache""" lowercase__ : Optional[Any] = os.path.join(lowercase_ , """tmp.sql""" ) lowercase__ : Union[str, Any] = SqlDatasetReader("""dataset""" , """sqlite:///""" + sqlite_path , cache_dir=lowercase_ ).read() SqlDatasetWriter(lowercase_ , """dataset""" , """sqlite:///""" + output_sqlite_path , num_proc=1 ).write() lowercase__ : Optional[Any] = iter_sql_file(lowercase_ ) lowercase__ : int = iter_sql_file(lowercase_ ) for rowa, rowa in zip(lowercase_ , lowercase_ ): assert rowa == rowa @require_sqlalchemy def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ ) -> str: '''simple docstring''' lowercase__ : List[str] = tmp_path / """cache""" lowercase__ : str = os.path.join(lowercase_ , """tmp.sql""" ) lowercase__ : List[str] = SqlDatasetReader("""dataset""" , """sqlite:///""" + sqlite_path , cache_dir=lowercase_ ).read() SqlDatasetWriter(lowercase_ , """dataset""" , """sqlite:///""" + output_sqlite_path , num_proc=2 ).write() lowercase__ : List[Any] = iter_sql_file(lowercase_ ) lowercase__ : Tuple = iter_sql_file(lowercase_ ) for rowa, rowa in zip(lowercase_ , lowercase_ ): assert rowa == rowa @require_sqlalchemy def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ ) -> Optional[Any]: '''simple docstring''' lowercase__ : Tuple = tmp_path / """cache""" lowercase__ : Union[str, Any] = os.path.join(lowercase_ , """tmp.sql""" ) lowercase__ : Dict = SqlDatasetReader("""dataset""" , """sqlite:///""" + sqlite_path , cache_dir=lowercase_ ).read() with pytest.raises(lowercase_ ): SqlDatasetWriter(lowercase_ , """dataset""" , """sqlite:///""" + output_sqlite_path , num_proc=0 ).write()
12
import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = { 'b0': efficientnet.EfficientNetBa, 'b1': efficientnet.EfficientNetBa, 'b2': efficientnet.EfficientNetBa, 'b3': efficientnet.EfficientNetBa, 'b4': efficientnet.EfficientNetBa, 'b5': efficientnet.EfficientNetBa, 'b6': efficientnet.EfficientNetBa, 'b7': efficientnet.EfficientNetBa, } SCREAMING_SNAKE_CASE__ : Optional[int] = { 'b0': { 'hidden_dim': 1_280, 'width_coef': 1.0, 'depth_coef': 1.0, 'image_size': 224, 'dropout_rate': 0.2, 'dw_padding': [], }, 'b1': { 'hidden_dim': 1_280, 'width_coef': 1.0, 'depth_coef': 1.1, 'image_size': 240, 'dropout_rate': 0.2, 'dw_padding': [16], }, 'b2': { 'hidden_dim': 1_408, 'width_coef': 1.1, 'depth_coef': 1.2, 'image_size': 260, 'dropout_rate': 0.3, 'dw_padding': [5, 8, 16], }, 'b3': { 'hidden_dim': 1_536, 'width_coef': 1.2, 'depth_coef': 1.4, 'image_size': 300, 'dropout_rate': 0.3, 'dw_padding': [5, 18], }, 'b4': { 'hidden_dim': 1_792, 'width_coef': 1.4, 'depth_coef': 1.8, 'image_size': 380, 'dropout_rate': 0.4, 'dw_padding': [6], }, 'b5': { 'hidden_dim': 2_048, 'width_coef': 1.6, 'depth_coef': 2.2, 'image_size': 456, 'dropout_rate': 0.4, 'dw_padding': [13, 27], }, 'b6': { 'hidden_dim': 2_304, 'width_coef': 1.8, 'depth_coef': 2.6, 'image_size': 528, 'dropout_rate': 0.5, 'dw_padding': [31], }, 'b7': { 'hidden_dim': 2_560, 'width_coef': 2.0, 'depth_coef': 3.1, 'image_size': 600, 'dropout_rate': 0.5, 'dw_padding': [18], }, } def a__ ( snake_case__ : Optional[Any] ): _UpperCAmelCase : Optional[int] = EfficientNetConfig() _UpperCAmelCase : Tuple = CONFIG_MAP[model_name]["""hidden_dim"""] _UpperCAmelCase : Any = CONFIG_MAP[model_name]["""width_coef"""] _UpperCAmelCase : Optional[Any] = CONFIG_MAP[model_name]["""depth_coef"""] _UpperCAmelCase : int = CONFIG_MAP[model_name]["""image_size"""] _UpperCAmelCase : List[str] = CONFIG_MAP[model_name]["""dropout_rate"""] _UpperCAmelCase : Optional[int] = CONFIG_MAP[model_name]["""dw_padding"""] _UpperCAmelCase : int = """huggingface/label-files""" _UpperCAmelCase : Dict = """imagenet-1k-id2label.json""" _UpperCAmelCase : Optional[Any] = 1000 _UpperCAmelCase : List[str] = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type="""dataset""" ) , """r""" ) ) _UpperCAmelCase : Union[str, Any] = {int(snake_case__ ): v for k, v in idalabel.items()} _UpperCAmelCase : Any = idalabel _UpperCAmelCase : List[str] = {v: k for k, v in idalabel.items()} return config def a__ ( ): _UpperCAmelCase : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" _UpperCAmelCase : str = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return im def a__ ( snake_case__ : Tuple ): _UpperCAmelCase : List[str] = CONFIG_MAP[model_name]["""image_size"""] _UpperCAmelCase : str = EfficientNetImageProcessor( size={"""height""": size, """width""": size} , image_mean=[0.485, 0.456, 0.406] , image_std=[0.4785_3944, 0.473_2864, 0.4743_4163] , do_center_crop=snake_case__ , ) return preprocessor def a__ ( snake_case__ : Optional[Any] ): _UpperCAmelCase : Optional[int] = [v.split("""_""" )[0].split("""block""" )[1] for v in original_param_names if v.startswith("""block""" )] _UpperCAmelCase : Dict = sorted(set(snake_case__ ) ) _UpperCAmelCase : int = len(snake_case__ ) _UpperCAmelCase : Optional[Any] = {b: str(snake_case__ ) for b, i in zip(snake_case__ , range(snake_case__ ) )} _UpperCAmelCase : Union[str, Any] = [] rename_keys.append(("""stem_conv/kernel:0""", """embeddings.convolution.weight""") ) rename_keys.append(("""stem_bn/gamma:0""", """embeddings.batchnorm.weight""") ) rename_keys.append(("""stem_bn/beta:0""", """embeddings.batchnorm.bias""") ) rename_keys.append(("""stem_bn/moving_mean:0""", """embeddings.batchnorm.running_mean""") ) rename_keys.append(("""stem_bn/moving_variance:0""", """embeddings.batchnorm.running_var""") ) for b in block_names: _UpperCAmelCase : List[Any] = block_name_mapping[b] rename_keys.append((f'''block{b}_expand_conv/kernel:0''', f'''encoder.blocks.{hf_b}.expansion.expand_conv.weight''') ) rename_keys.append((f'''block{b}_expand_bn/gamma:0''', f'''encoder.blocks.{hf_b}.expansion.expand_bn.weight''') ) rename_keys.append((f'''block{b}_expand_bn/beta:0''', f'''encoder.blocks.{hf_b}.expansion.expand_bn.bias''') ) rename_keys.append( (f'''block{b}_expand_bn/moving_mean:0''', f'''encoder.blocks.{hf_b}.expansion.expand_bn.running_mean''') ) rename_keys.append( (f'''block{b}_expand_bn/moving_variance:0''', f'''encoder.blocks.{hf_b}.expansion.expand_bn.running_var''') ) rename_keys.append( (f'''block{b}_dwconv/depthwise_kernel:0''', f'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight''') ) rename_keys.append((f'''block{b}_bn/gamma:0''', f'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight''') ) rename_keys.append((f'''block{b}_bn/beta:0''', f'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias''') ) rename_keys.append( (f'''block{b}_bn/moving_mean:0''', f'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean''') ) rename_keys.append( (f'''block{b}_bn/moving_variance:0''', f'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var''') ) rename_keys.append((f'''block{b}_se_reduce/kernel:0''', f'''encoder.blocks.{hf_b}.squeeze_excite.reduce.weight''') ) rename_keys.append((f'''block{b}_se_reduce/bias:0''', f'''encoder.blocks.{hf_b}.squeeze_excite.reduce.bias''') ) rename_keys.append((f'''block{b}_se_expand/kernel:0''', f'''encoder.blocks.{hf_b}.squeeze_excite.expand.weight''') ) rename_keys.append((f'''block{b}_se_expand/bias:0''', f'''encoder.blocks.{hf_b}.squeeze_excite.expand.bias''') ) rename_keys.append( (f'''block{b}_project_conv/kernel:0''', f'''encoder.blocks.{hf_b}.projection.project_conv.weight''') ) rename_keys.append((f'''block{b}_project_bn/gamma:0''', f'''encoder.blocks.{hf_b}.projection.project_bn.weight''') ) rename_keys.append((f'''block{b}_project_bn/beta:0''', f'''encoder.blocks.{hf_b}.projection.project_bn.bias''') ) rename_keys.append( (f'''block{b}_project_bn/moving_mean:0''', f'''encoder.blocks.{hf_b}.projection.project_bn.running_mean''') ) rename_keys.append( (f'''block{b}_project_bn/moving_variance:0''', f'''encoder.blocks.{hf_b}.projection.project_bn.running_var''') ) rename_keys.append(("""top_conv/kernel:0""", """encoder.top_conv.weight""") ) rename_keys.append(("""top_bn/gamma:0""", """encoder.top_bn.weight""") ) rename_keys.append(("""top_bn/beta:0""", """encoder.top_bn.bias""") ) rename_keys.append(("""top_bn/moving_mean:0""", """encoder.top_bn.running_mean""") ) rename_keys.append(("""top_bn/moving_variance:0""", """encoder.top_bn.running_var""") ) _UpperCAmelCase : Union[str, Any] = {} for item in rename_keys: if item[0] in original_param_names: _UpperCAmelCase : Tuple = """efficientnet.""" + item[1] _UpperCAmelCase : List[Any] = """classifier.weight""" _UpperCAmelCase : List[Any] = """classifier.bias""" return key_mapping def a__ ( snake_case__ : Optional[int] , snake_case__ : int , snake_case__ : List[str] ): for key, value in tf_params.items(): if "normalization" in key: continue _UpperCAmelCase : Optional[Any] = key_mapping[key] if "_conv" in key and "kernel" in key: _UpperCAmelCase : Optional[Any] = torch.from_numpy(snake_case__ ).permute(3 , 2 , 0 , 1 ) elif "depthwise_kernel" in key: _UpperCAmelCase : Dict = torch.from_numpy(snake_case__ ).permute(2 , 3 , 0 , 1 ) elif "kernel" in key: _UpperCAmelCase : Any = torch.from_numpy(np.transpose(snake_case__ ) ) else: _UpperCAmelCase : Optional[Any] = torch.from_numpy(snake_case__ ) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(snake_case__ ) @torch.no_grad() def a__ ( snake_case__ : str , snake_case__ : Dict , snake_case__ : int , snake_case__ : str ): _UpperCAmelCase : List[str] = model_classes[model_name]( include_top=snake_case__ , weights="""imagenet""" , input_tensor=snake_case__ , input_shape=snake_case__ , pooling=snake_case__ , classes=1000 , classifier_activation="""softmax""" , ) _UpperCAmelCase : Any = original_model.trainable_variables _UpperCAmelCase : List[Any] = original_model.non_trainable_variables _UpperCAmelCase : List[Any] = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: _UpperCAmelCase : List[str] = param.numpy() _UpperCAmelCase : List[Any] = list(tf_params.keys() ) # Load HuggingFace model _UpperCAmelCase : Any = get_efficientnet_config(snake_case__ ) _UpperCAmelCase : List[str] = EfficientNetForImageClassification(snake_case__ ).eval() _UpperCAmelCase : Any = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print("""Converting parameters...""" ) _UpperCAmelCase : Optional[Any] = rename_keys(snake_case__ ) replace_params(snake_case__ , snake_case__ , snake_case__ ) # Initialize preprocessor and preprocess input image _UpperCAmelCase : Dict = convert_image_processor(snake_case__ ) _UpperCAmelCase : List[Any] = preprocessor(images=prepare_img() , return_tensors="""pt""" ) # HF model inference hf_model.eval() with torch.no_grad(): _UpperCAmelCase : List[str] = hf_model(**snake_case__ ) _UpperCAmelCase : Any = outputs.logits.detach().numpy() # Original model inference _UpperCAmelCase : Dict = False _UpperCAmelCase : List[Any] = CONFIG_MAP[model_name]["""image_size"""] _UpperCAmelCase : Any = prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST ) _UpperCAmelCase : Optional[Any] = image.img_to_array(snake_case__ ) _UpperCAmelCase : Any = np.expand_dims(snake_case__ , axis=0 ) _UpperCAmelCase : List[Any] = original_model.predict(snake_case__ ) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(snake_case__ , snake_case__ , atol=1e-3 ), "The predicted logits are not the same." print("""Model outputs match!""" ) if save_model: # Create folder to save model if not os.path.isdir(snake_case__ ): os.mkdir(snake_case__ ) # Save converted model and image processor hf_model.save_pretrained(snake_case__ ) preprocessor.save_pretrained(snake_case__ ) if push_to_hub: # Push model and image processor to hub print(f'''Pushing converted {model_name} to the hub...''' ) _UpperCAmelCase : int = f'''efficientnet-{model_name}''' preprocessor.push_to_hub(snake_case__ ) hf_model.push_to_hub(snake_case__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='b0', type=str, help='Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].', ) parser.add_argument( '--pytorch_dump_folder_path', default='hf_model', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--save_model', action='store_true', help='Save model to local') parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
643
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() A = logging.get_logger(__name__) def lowerCamelCase ( UpperCamelCase : str , UpperCamelCase : Any=False , UpperCamelCase : Union[str, Any]=False , UpperCamelCase : List[Any]=False ) -> List[str]: _lowerCamelCase = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""transformer.blocks.{i}.norm1.weight""", F"""vilt.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.norm1.bias""", F"""vilt.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""transformer.blocks.{i}.attn.proj.weight""", F"""vilt.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append( (F"""transformer.blocks.{i}.attn.proj.bias""", F"""vilt.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""transformer.blocks.{i}.norm2.weight""", F"""vilt.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.norm2.bias""", F"""vilt.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append( (F"""transformer.blocks.{i}.mlp.fc1.weight""", F"""vilt.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.mlp.fc1.bias""", F"""vilt.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""transformer.blocks.{i}.mlp.fc2.weight""", F"""vilt.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.mlp.fc2.bias""", F"""vilt.encoder.layer.{i}.output.dense.bias""") ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def lowerCamelCase ( UpperCamelCase : str , UpperCamelCase : str ) -> Tuple: for i in range(config.num_hidden_layers ): _lowerCamelCase = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _lowerCamelCase = state_dict.pop(F"""transformer.blocks.{i}.attn.qkv.weight""" ) _lowerCamelCase = state_dict.pop(F"""transformer.blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict _lowerCamelCase = in_proj_weight[ : config.hidden_size, : ] _lowerCamelCase = in_proj_bias[: config.hidden_size] _lowerCamelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _lowerCamelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _lowerCamelCase = in_proj_weight[ -config.hidden_size :, : ] _lowerCamelCase = in_proj_bias[-config.hidden_size :] def lowerCamelCase ( UpperCamelCase : Tuple ) -> List[Any]: _lowerCamelCase = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(UpperCamelCase , UpperCamelCase ) def lowerCamelCase ( UpperCamelCase : Tuple , UpperCamelCase : Optional[Any] , UpperCamelCase : str ) -> Any: _lowerCamelCase = dct.pop(UpperCamelCase ) _lowerCamelCase = val @torch.no_grad() def lowerCamelCase ( UpperCamelCase : int , UpperCamelCase : int ) -> Optional[int]: _lowerCamelCase = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=UpperCamelCase ) _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False if "vqa" in checkpoint_url: _lowerCamelCase = True _lowerCamelCase = 31_29 _lowerCamelCase = 'huggingface/label-files' _lowerCamelCase = 'vqa2-id2label.json' _lowerCamelCase = json.load(open(hf_hub_download(UpperCamelCase , UpperCamelCase , repo_type='dataset' ) , 'r' ) ) _lowerCamelCase = {int(UpperCamelCase ): v for k, v in idalabel.items()} _lowerCamelCase = idalabel _lowerCamelCase = {v: k for k, v in idalabel.items()} _lowerCamelCase = ViltForQuestionAnswering(UpperCamelCase ) elif "nlvr" in checkpoint_url: _lowerCamelCase = True _lowerCamelCase = 2 _lowerCamelCase = {0: 'False', 1: 'True'} _lowerCamelCase = {v: k for k, v in config.idalabel.items()} _lowerCamelCase = 3 _lowerCamelCase = ViltForImagesAndTextClassification(UpperCamelCase ) elif "irtr" in checkpoint_url: _lowerCamelCase = True _lowerCamelCase = ViltForImageAndTextRetrieval(UpperCamelCase ) elif "mlm_itm" in checkpoint_url: _lowerCamelCase = True _lowerCamelCase = ViltForMaskedLM(UpperCamelCase ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys _lowerCamelCase = torch.hub.load_state_dict_from_url(UpperCamelCase , map_location='cpu' )['state_dict'] _lowerCamelCase = create_rename_keys(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) for src, dest in rename_keys: rename_key(UpperCamelCase , UpperCamelCase , UpperCamelCase ) read_in_q_k_v(UpperCamelCase , UpperCamelCase ) if mlm_model or irtr_model: _lowerCamelCase = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(UpperCamelCase , UpperCamelCase ) # load state dict into HuggingFace model model.eval() if mlm_model: _lowerCamelCase , _lowerCamelCase = model.load_state_dict(UpperCamelCase , strict=UpperCamelCase ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(UpperCamelCase ) # Define processor _lowerCamelCase = ViltImageProcessor(size=3_84 ) _lowerCamelCase = BertTokenizer.from_pretrained('bert-base-uncased' ) _lowerCamelCase = ViltProcessor(UpperCamelCase , UpperCamelCase ) # Forward pass on example inputs (image + text) if nlvr_model: _lowerCamelCase = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=UpperCamelCase ).raw ) _lowerCamelCase = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=UpperCamelCase ).raw ) _lowerCamelCase = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) _lowerCamelCase = processor(UpperCamelCase , UpperCamelCase , return_tensors='pt' ) _lowerCamelCase = processor(UpperCamelCase , UpperCamelCase , return_tensors='pt' ) _lowerCamelCase = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: _lowerCamelCase = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=UpperCamelCase ).raw ) if mlm_model: _lowerCamelCase = 'a bunch of [MASK] laying on a [MASK].' else: _lowerCamelCase = 'How many cats are there?' _lowerCamelCase = processor(UpperCamelCase , UpperCamelCase , return_tensors='pt' ) _lowerCamelCase = model(**UpperCamelCase ) # Verify outputs if mlm_model: _lowerCamelCase = torch.Size([1, 11, 3_05_22] ) _lowerCamelCase = torch.tensor([-12.5_061, -12.5_123, -12.5_174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , UpperCamelCase , atol=1e-4 ) # verify masked token prediction equals "cats" _lowerCamelCase = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: _lowerCamelCase = torch.Size([1, 31_29] ) _lowerCamelCase = torch.tensor([-15.9_495, -18.1_472, -10.3_041] ) assert torch.allclose(outputs.logits[0, :3] , UpperCamelCase , atol=1e-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , UpperCamelCase , atol=1e-4 ) # verify vqa prediction equals "2" _lowerCamelCase = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: _lowerCamelCase = torch.Size([1, 2] ) _lowerCamelCase = torch.tensor([-2.8_721, 2.1_291] ) assert torch.allclose(outputs.logits[0, :3] , UpperCamelCase , atol=1e-4 ) assert outputs.logits.shape == expected_shape Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) print(F"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(UpperCamelCase ) processor.save_pretrained(UpperCamelCase ) if __name__ == "__main__": A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) A = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
234
from itertools import product def lowerCamelCase ( UpperCamelCase : int , UpperCamelCase : int ) -> list[int]: _lowerCamelCase = sides_number _lowerCamelCase = max_face_number * dice_number _lowerCamelCase = [0] * (max_total + 1) _lowerCamelCase = 1 _lowerCamelCase = range(UpperCamelCase , max_face_number + 1 ) for dice_numbers in product(UpperCamelCase , repeat=UpperCamelCase ): _lowerCamelCase = sum(UpperCamelCase ) totals_frequencies[total] += 1 return totals_frequencies def lowerCamelCase ( ) -> float: _lowerCamelCase = total_frequency_distribution( sides_number=4 , dice_number=9 ) _lowerCamelCase = total_frequency_distribution( sides_number=6 , dice_number=6 ) _lowerCamelCase = 0 _lowerCamelCase = 9 _lowerCamelCase = 4 * 9 _lowerCamelCase = 6 for peter_total in range(UpperCamelCase , max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) _lowerCamelCase = (4**9) * (6**6) _lowerCamelCase = peter_wins_count / total_games_number _lowerCamelCase = round(UpperCamelCase , ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(F'''{solution() = }''')
234
1
import math import sys import cva import numpy as np def _A ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : float ): # For applying gaussian function for each element in matrix. UpperCamelCase :Tuple = math.sqrt(_lowercase ) UpperCamelCase :List[Any] = 1 / (sigma * math.sqrt(2 * math.pi )) return cons * np.exp(-((img / sigma) ** 2) * 0.5 ) def _A ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Optional[Any] = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float ): # Creates a gaussian kernel of given dimension. UpperCamelCase :List[Any] = np.zeros((kernel_size, kernel_size) ) for i in range(0 , _lowercase ): for j in range(0 , _lowercase ): UpperCamelCase :Optional[int] = math.sqrt( abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 ) return vec_gaussian(_lowercase , _lowercase ) def _A ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : int , ): UpperCamelCase :Any = np.zeros(img.shape ) UpperCamelCase :Optional[Any] = get_gauss_kernel(_lowercase , _lowercase ) UpperCamelCase :Tuple = img.shape for i in range(kernel_size // 2 , size_x - kernel_size // 2 ): for j in range(kernel_size // 2 , size_y - kernel_size // 2 ): UpperCamelCase :Tuple = get_slice(_lowercase , _lowercase , _lowercase , _lowercase ) UpperCamelCase :Dict = img_s - img_s[kernel_size // 2, kernel_size // 2] UpperCamelCase :Optional[int] = vec_gaussian(_lowercase , _lowercase ) UpperCamelCase :Tuple = np.multiply(_lowercase , _lowercase ) UpperCamelCase :int = np.multiply(_lowercase , _lowercase ) UpperCamelCase :Tuple = np.sum(_lowercase ) / np.sum(_lowercase ) UpperCamelCase :Optional[int] = val return imga def _A ( SCREAMING_SNAKE_CASE__ : list ): UpperCamelCase :Tuple = args[1] if args[1:] else """../image_data/lena.jpg""" UpperCamelCase :Optional[Any] = float(args[2] ) if args[2:] else 1.0 UpperCamelCase :str = float(args[3] ) if args[3:] else 1.0 if args[4:]: UpperCamelCase :Optional[Any] = int(args[4] ) UpperCamelCase :Optional[int] = kernel_size + abs(kernel_size % 2 - 1 ) else: UpperCamelCase :Any = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": __snake_case , __snake_case , __snake_case , __snake_case = parse_args(sys.argv) __snake_case = cva.imread(filename, 0) cva.imshow("""input image""", img) __snake_case = img / 2_55 __snake_case = out.astype("""float32""") __snake_case = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) __snake_case = out * 2_55 __snake_case = np.uinta(out) cva.imshow("""output image""", out) cva.waitKey(0) cva.destroyAllWindows()
658
'''simple docstring''' # Algorithm for the pigeonhole sorting def UpperCamelCase__ ( _lowercase : Any ) -> List[Any]: __UpperCAmelCase: List[Any] = min(_lowercase ) # min() finds the minimum value __UpperCAmelCase: List[str] = max(_lowercase ) # max() finds the maximum value __UpperCAmelCase: Dict = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size __UpperCAmelCase: str = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(_lowercase , _lowercase ), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. __UpperCAmelCase: List[str] = 0 for count in range(_lowercase ): while holes[count] > 0: holes[count] -= 1 __UpperCAmelCase: Optional[int] = count + min_val i += 1 def UpperCamelCase__ ( ) -> Optional[int]: __UpperCAmelCase: Union[str, Any] = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(_lowercase ) print("""Sorted order is:""" , """ """.join(_lowercase ) ) if __name__ == "__main__": main()
523
0
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator class A__ : '''simple docstring''' def __init__( self: Any , _SCREAMING_SNAKE_CASE: int) -> None: """simple docstring""" __lowerCAmelCase : Optional[Any] = value __lowerCAmelCase : Node | None = None __lowerCAmelCase : Node | None = None class A__ : '''simple docstring''' def __init__( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Node) -> None: """simple docstring""" __lowerCAmelCase : Tuple = tree def _SCREAMING_SNAKE_CASE ( self: List[str] , _SCREAMING_SNAKE_CASE: Node | None) -> int: """simple docstring""" if node is None: return 0 return node.value + ( self.depth_first_search(node.left) + self.depth_first_search(node.right) ) def __iter__( self: Union[str, Any]) -> Iterator[int]: """simple docstring""" yield self.depth_first_search(self.tree) if __name__ == "__main__": import doctest doctest.testmod()
712
"""simple docstring""" import re from filelock import FileLock try: import nltk __snake_case : Any = True except (ImportError, ModuleNotFoundError): __snake_case : Optional[int] = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _lowercase ( __snake_case ) -> str: re.sub("<n>" ,"" ,__snake_case ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(__snake_case ) )
615
0
'''simple docstring''' import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, require_torch, 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class UpperCamelCase__: def __init__( self : List[str] , lowerCAmelCase : Dict , lowerCAmelCase : Tuple=13 , lowerCAmelCase : List[str]=64 , lowerCAmelCase : List[Any]=2 , lowerCAmelCase : str=3 , lowerCAmelCase : Optional[int]=True , lowerCAmelCase : Union[str, Any]=True , lowerCAmelCase : str=32 , lowerCAmelCase : Optional[Any]=5 , lowerCAmelCase : Tuple=4 , lowerCAmelCase : Optional[int]=37 , lowerCAmelCase : Union[str, Any]="gelu" , lowerCAmelCase : Optional[Any]=0.1 , lowerCAmelCase : str=0.1 , lowerCAmelCase : int=10 , lowerCAmelCase : Tuple=0.02 , lowerCAmelCase : str=[1, 16, 4, 4] , lowerCAmelCase : Optional[Any]=None , )-> Dict: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = is_training UpperCAmelCase = use_labels UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = scope UpperCAmelCase = backbone_featmap_shape # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) # the number of patches is based on the feature map of the backbone, which by default uses an output stride # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size UpperCAmelCase = (self.image_size // 32) ** 2 UpperCAmelCase = num_patches + 1 def a__( self : int )-> Union[str, Any]: """simple docstring""" UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = self.get_config() return config, pixel_values, labels def a__( self : List[Any] )-> List[str]: """simple docstring""" UpperCAmelCase = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [4, 8, 16, 32], '''num_groups''': 2, } return ViTHybridConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCAmelCase , initializer_range=self.initializer_range , backbone_featmap_shape=self.backbone_featmap_shape , backbone_config=lowerCAmelCase , ) def a__( self : Dict , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Tuple , lowerCAmelCase : Union[str, Any] )-> List[Any]: """simple docstring""" UpperCAmelCase = ViTHybridModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() UpperCAmelCase = model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__( self : int , lowerCAmelCase : Any , lowerCAmelCase : Optional[Any] , lowerCAmelCase : int )-> Optional[int]: """simple docstring""" UpperCAmelCase = self.type_sequence_label_size UpperCAmelCase = ViTHybridForImageClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() UpperCAmelCase = model(lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__( self : Any )-> List[Any]: """simple docstring""" UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = config_and_inputs UpperCAmelCase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCamelCase__( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): __magic_name__ : List[Any] = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () __magic_name__ : List[Any] = ( {"feature-extraction": ViTHybridModel, "image-classification": ViTHybridForImageClassification} if is_torch_available() else {} ) __magic_name__ : Dict = False __magic_name__ : Union[str, Any] = False __magic_name__ : Optional[int] = False def a__( self : Optional[int] )-> Optional[Any]: """simple docstring""" UpperCAmelCase = ViTHybridModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=lowerCAmelCase , has_text_modality=lowerCAmelCase , hidden_size=37 ) def a__( self : List[Any] )-> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def a__( self : List[Any] )-> Optional[Any]: """simple docstring""" pass def a__( self : Optional[Any] )-> Optional[int]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase , nn.Linear ) ) def a__( self : Tuple )-> Dict: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase = model_class(lowerCAmelCase ) UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase = [*signature.parameters.keys()] UpperCAmelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCAmelCase ) def a__( self : Optional[int] )-> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def a__( self : Optional[int] )-> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase ) def a__( self : Any )-> Union[str, Any]: """simple docstring""" UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase = _config_zero_init(lowerCAmelCase ) for model_class in self.all_model_classes: UpperCAmelCase = model_class(config=lowerCAmelCase ) # Skip the check for the backbone for name, module in model.named_modules(): if module.__class__.__name__ == "ViTHybridPatchEmbeddings": UpperCAmelCase = [F"""{name}.{key}""" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @slow def a__( self : Any )-> Union[str, Any]: """simple docstring""" for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = ViTHybridModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) def lowerCamelCase__ ( ): '''simple docstring''' UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class UpperCamelCase__( unittest.TestCase ): @cached_property def a__( self : Tuple )-> int: """simple docstring""" return ( ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def a__( self : Dict )-> Dict: """simple docstring""" UpperCAmelCase = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( lowerCAmelCase ) UpperCAmelCase = self.default_image_processor UpperCAmelCase = prepare_img() UpperCAmelCase = image_processor(images=lowerCAmelCase , return_tensors='''pt''' ).to(lowerCAmelCase ) # forward pass with torch.no_grad(): UpperCAmelCase = model(**lowerCAmelCase ) # verify the logits UpperCAmelCase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase ) UpperCAmelCase = torch.tensor([-1.9090, -0.4993, -0.2389] ).to(lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase , atol=1E-4 ) ) @slow @require_accelerate def a__( self : str )-> Tuple: """simple docstring""" UpperCAmelCase = ViTHybridImageProcessor.from_pretrained('''google/vit-hybrid-base-bit-384''' ) UpperCAmelCase = ViTHybridForImageClassification.from_pretrained('''google/vit-hybrid-base-bit-384''' , device_map='''auto''' ) UpperCAmelCase = prepare_img() UpperCAmelCase = image_processor(images=lowerCAmelCase , return_tensors='''pt''' ) UpperCAmelCase = model(**lowerCAmelCase ) UpperCAmelCase = outputs.logits # model predicts one of the 1000 ImageNet classes UpperCAmelCase = logits.argmax(-1 ).item() self.assertTrue(model.config.idalabel[predicted_class_idx] , '''tabby, tabby cat''' )
210
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCamelCase__( unittest.TestCase ): @property def a__( self : List[str] )-> Dict: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase = 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 a__( self : Tuple )-> int: """simple docstring""" UpperCAmelCase = self.dummy_uncond_unet UpperCAmelCase = PNDMScheduler() UpperCAmelCase = PNDMPipeline(unet=lowerCAmelCase , scheduler=lowerCAmelCase ) pndm.to(lowerCAmelCase ) pndm.set_progress_bar_config(disable=lowerCAmelCase ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = pndm(generator=lowerCAmelCase , num_inference_steps=20 , output_type='''numpy''' ).images UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = pndm(generator=lowerCAmelCase , num_inference_steps=20 , output_type='''numpy''' , return_dict=lowerCAmelCase )[0] UpperCAmelCase = image[0, -3:, -3:, -1] UpperCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase = 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 UpperCamelCase__( unittest.TestCase ): def a__( self : Dict )-> List[str]: """simple docstring""" UpperCAmelCase = '''google/ddpm-cifar10-32''' UpperCAmelCase = UNetaDModel.from_pretrained(lowerCAmelCase ) UpperCAmelCase = PNDMScheduler() UpperCAmelCase = PNDMPipeline(unet=lowerCAmelCase , scheduler=lowerCAmelCase ) pndm.to(lowerCAmelCase ) pndm.set_progress_bar_config(disable=lowerCAmelCase ) UpperCAmelCase = torch.manual_seed(0 ) UpperCAmelCase = pndm(generator=lowerCAmelCase , output_type='''numpy''' ).images UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
210
1
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler lowerCamelCase = 16 lowerCamelCase = 32 def a__ ( lowerCAmelCase__ , lowerCAmelCase__ = 16 , lowerCAmelCase__ = "bert-base-cased" ): UpperCAmelCase_ = AutoTokenizer.from_pretrained(lowerCAmelCase__ ) UpperCAmelCase_ = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase__ ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase_ = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase_ = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=["idx", "sentence1", "sentence2"] , load_from_cache_file=lowerCAmelCase__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase_ = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(lowerCAmelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase__ , padding="max_length" , max_length=128 , return_tensors="pt" ) return tokenizer.pad(lowerCAmelCase__ , padding="longest" , return_tensors="pt" ) # Instantiate dataloaders. UpperCAmelCase_ = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) UpperCAmelCase_ = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) return train_dataloader, eval_dataloader def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): model.eval() UpperCAmelCase_ = 0 for step, batch in enumerate(lowerCAmelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase_ = model(**lowerCAmelCase__ ) UpperCAmelCase_ = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCAmelCase_ , UpperCAmelCase_ = accelerator.gather( (predictions, batch["labels"]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowerCAmelCase__ ) - 1: UpperCAmelCase_ = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCAmelCase_ = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowerCAmelCase__ , references=lowerCAmelCase__ , ) UpperCAmelCase_ = metric.compute() return eval_metric["accuracy"] def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ): # Initialize accelerator UpperCAmelCase_ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase_ = config["lr"] UpperCAmelCase_ = int(config["num_epochs"] ) UpperCAmelCase_ = int(config["seed"] ) UpperCAmelCase_ = int(config["batch_size"] ) UpperCAmelCase_ = args.model_name_or_path set_seed(lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_ = get_dataloaders(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase_ = AutoModelForSequenceClassification.from_pretrained(lowerCAmelCase__ , return_dict=lowerCAmelCase__ ) # Instantiate optimizer UpperCAmelCase_ = ( AdamW if accelerator.state.deepspeed_plugin is None or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase_ = optimizer_cls(params=model.parameters() , lr=lowerCAmelCase__ ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase_ = accelerator.state.deepspeed_plugin.deepspeed_config[ "gradient_accumulation_steps" ] else: UpperCAmelCase_ = 1 UpperCAmelCase_ = (len(lowerCAmelCase__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase_ = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase__ , num_warmup_steps=0 , num_training_steps=lowerCAmelCase__ , ) else: UpperCAmelCase_ = DummyScheduler(lowerCAmelCase__ , total_num_steps=lowerCAmelCase__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = accelerator.prepare( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase_ = 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase_ = 0 UpperCAmelCase_ = evaluate.load("glue" , "mrpc" ) UpperCAmelCase_ = num_epochs if args.partial_train_epoch is not None: UpperCAmelCase_ = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) UpperCAmelCase_ = args.resume_from_checkpoint.split("epoch_" )[1] UpperCAmelCase_ = "" for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break UpperCAmelCase_ = int(lowerCAmelCase__ ) + 1 UpperCAmelCase_ = evaluation_loop(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) accelerator.print("resumed checkpoint performance:" , lowerCAmelCase__ ) accelerator.print("resumed checkpoint's scheduler's lr:" , lr_scheduler.get_lr()[0] ) accelerator.print("resumed optimizers's lr:" , optimizer.param_groups[0]["lr"] ) with open(os.path.join(args.output_dir , f"""state_{starting_epoch-1}.json""" ) , "r" ) as f: UpperCAmelCase_ = json.load(lowerCAmelCase__ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model UpperCAmelCase_ = {} for epoch in range(lowerCAmelCase__ , lowerCAmelCase__ ): model.train() for step, batch in enumerate(lowerCAmelCase__ ): UpperCAmelCase_ = model(**lowerCAmelCase__ ) UpperCAmelCase_ = outputs.loss UpperCAmelCase_ = loss / gradient_accumulation_steps accelerator.backward(lowerCAmelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 UpperCAmelCase_ = f"""epoch_{epoch}""" UpperCAmelCase_ = os.path.join(args.output_dir , lowerCAmelCase__ ) accelerator.save_state(lowerCAmelCase__ ) UpperCAmelCase_ = evaluation_loop(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) UpperCAmelCase_ = accuracy UpperCAmelCase_ = lr_scheduler.get_lr()[0] UpperCAmelCase_ = optimizer.param_groups[0]["lr"] UpperCAmelCase_ = epoch UpperCAmelCase_ = overall_step accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , f"""state_{epoch}.json""" ) , "w" ) as f: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def a__ ( ): UpperCAmelCase_ = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage." ) parser.add_argument( "--model_name_or_path" , type=lowerCAmelCase__ , default="bert-base-cased" , help="Path to pretrained model or model identifier from huggingface.co/models." , required=lowerCAmelCase__ , ) parser.add_argument( "--output_dir" , type=lowerCAmelCase__ , default="." , help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory." , ) parser.add_argument( "--resume_from_checkpoint" , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help="If the training should continue from a checkpoint folder." , ) parser.add_argument( "--partial_train_epoch" , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help="If passed, the training will stop after this number of epochs." , ) parser.add_argument( "--num_epochs" , type=lowerCAmelCase__ , default=2 , help="Number of train epochs." , ) UpperCAmelCase_ = parser.parse_args() UpperCAmelCase_ = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": main()
14
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowerCamelCase = { """text_branch""": """text_model""", """audio_branch""": """audio_model.audio_encoder""", """attn""": """attention.self""", """self.proj""": """output.dense""", """attention.self_mask""": """attn_mask""", """mlp.fc1""": """intermediate.dense""", """mlp.fc2""": """output.dense""", """norm1""": """layernorm_before""", """norm2""": """layernorm_after""", """bn0""": """batch_norm""", } lowerCamelCase = AutoFeatureExtractor.from_pretrained("""laion/clap-htsat-unfused""", truncation="""rand_trunc""") def a__ ( lowerCAmelCase__ , lowerCAmelCase__=False ): UpperCAmelCase_ , UpperCAmelCase_ = create_model( "HTSAT-tiny" , "roberta" , lowerCAmelCase__ , precision="fp32" , device="cuda:0" if torch.cuda.is_available() else "cpu" , enable_fusion=lowerCAmelCase__ , fusion_type="aff_2d" if enable_fusion else None , ) return model, model_cfg def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = {} UpperCAmelCase_ = r".*sequential.(\d+).*" UpperCAmelCase_ = r".*_projection.(\d+).*" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: UpperCAmelCase_ = key.replace(lowerCAmelCase__ , lowerCAmelCase__ ) if re.match(lowerCAmelCase__ , lowerCAmelCase__ ): # replace sequential layers with list UpperCAmelCase_ = re.match(lowerCAmelCase__ , lowerCAmelCase__ ).group(1 ) UpperCAmelCase_ = key.replace(f"""sequential.{sequential_layer}.""" , f"""layers.{int(lowerCAmelCase__ )//3}.linear.""" ) elif re.match(lowerCAmelCase__ , lowerCAmelCase__ ): UpperCAmelCase_ = int(re.match(lowerCAmelCase__ , lowerCAmelCase__ ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... UpperCAmelCase_ = 1 if projecton_layer == 0 else 2 UpperCAmelCase_ = key.replace(f"""_projection.{projecton_layer}.""" , f"""_projection.linear{transformers_projection_layer}.""" ) if "audio" and "qkv" in key: # split qkv into query key and value UpperCAmelCase_ = value UpperCAmelCase_ = mixed_qkv.size(0 ) // 3 UpperCAmelCase_ = mixed_qkv[:qkv_dim] UpperCAmelCase_ = mixed_qkv[qkv_dim : qkv_dim * 2] UpperCAmelCase_ = mixed_qkv[qkv_dim * 2 :] UpperCAmelCase_ = query_layer UpperCAmelCase_ = key_layer UpperCAmelCase_ = value_layer else: UpperCAmelCase_ = value return model_state_dict def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False ): UpperCAmelCase_ , UpperCAmelCase_ = init_clap(lowerCAmelCase__ , enable_fusion=lowerCAmelCase__ ) clap_model.eval() UpperCAmelCase_ = clap_model.state_dict() UpperCAmelCase_ = rename_state_dict(lowerCAmelCase__ ) UpperCAmelCase_ = ClapConfig() UpperCAmelCase_ = enable_fusion UpperCAmelCase_ = ClapModel(lowerCAmelCase__ ) # ignore the spectrogram embedding layer model.load_state_dict(lowerCAmelCase__ , strict=lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) transformers_config.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": lowerCamelCase = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument("""--enable_fusion""", action="""store_true""", help="""Whether to enable fusion or not""") lowerCamelCase = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
14
1
import unittest from transformers import AutoTokenizer, FalconConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class UpperCamelCase_ : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple=3 , UpperCAmelCase__ : List[Any]=7 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Any=99 , UpperCAmelCase__ : Optional[int]=32 , UpperCAmelCase__ : str=5 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : str=37 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Any=512 , UpperCAmelCase__ : Union[str, Any]=16 , UpperCAmelCase__ : Tuple=2 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : List[Any]=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : Union[str, Any]=None , ) ->Optional[Any]: '''simple docstring''' 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 SCREAMING_SNAKE_CASE ( self : List[str]) ->Tuple: '''simple docstring''' 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 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 SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Optional[int]: '''simple docstring''' return FalconConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=UpperCAmelCase__ , ) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str]) ->List[str]: '''simple docstring''' A__ = FalconModel(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__) A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , ) ->Optional[int]: '''simple docstring''' A__ = True A__ = FalconModel(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , ) ->int: '''simple docstring''' A__ = FalconForCausalLM(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , ) ->Optional[int]: '''simple docstring''' A__ = True A__ = True A__ = FalconForCausalLM(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() # first forward pass A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , ) A__ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size) A__ = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and A__ = torch.cat([input_ids, next_tokens] , dim=-1) A__ = torch.cat([input_mask, next_mask] , dim=-1) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] # select random slice A__ = ids_tensor((1,) , output_from_past.shape[-1]).item() A__ = output_from_no_past[:, -3:, random_slice_idx].detach() A__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3)) def SCREAMING_SNAKE_CASE ( self : int) ->List[str]: '''simple docstring''' A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) UpperCAmelCase__ = (FalconForCausalLM,) if is_torch_available() else () UpperCAmelCase__ = ( { '''feature-extraction''': FalconModel, '''text-classification''': FalconForSequenceClassification, '''text-generation''': FalconForCausalLM, '''question-answering''': FalconForQuestionAnswering, '''token-classification''': FalconForTokenClassification, '''zero-shot''': FalconForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase__ = False UpperCAmelCase__ = False def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Tuple: '''simple docstring''' A__ = FalconModelTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37) def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[str]) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Union[str, Any]: '''simple docstring''' A__ , *A__ = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: A__ = alibi self.model_tester.create_and_check_model(UpperCAmelCase__ , *UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->Optional[Any]: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = 3 A__ = input_dict['''input_ids'''] A__ = input_ids.ne(1).to(UpperCAmelCase__) A__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) A__ = FalconForSequenceClassification(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[Any]: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = 3 A__ = '''single_label_classification''' A__ = input_dict['''input_ids'''] A__ = input_ids.ne(1).to(UpperCAmelCase__) A__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) A__ = FalconForSequenceClassification(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Dict: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = input_dict['''input_ids'''] A__ = FalconForCausalLM(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__) A__ = input_ids.shape[0] A__ = model._convert_to_rw_cache(result.past_key_values) A__ = model._convert_cache_to_standard_format(UpperCAmelCase__ , UpperCAmelCase__) for layer in range(len(UpperCAmelCase__)): for tensor_idx in range(2): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx])) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = 3 A__ = '''multi_label_classification''' A__ = input_dict['''input_ids'''] A__ = input_ids.ne(1).to(UpperCAmelCase__) A__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) A__ = FalconForSequenceClassification(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[str]: '''simple docstring''' for model_class in self.all_generative_model_classes: A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(UpperCAmelCase__ , '''use_cache'''): return A__ = model_class(UpperCAmelCase__).to(UpperCAmelCase__) if "use_cache" not in inputs: A__ = True A__ = model(**UpperCAmelCase__) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return A__ = ( getattr(UpperCAmelCase__ , '''decoder_layers''' , UpperCAmelCase__) or getattr(UpperCAmelCase__ , '''num_decoder_layers''' , UpperCAmelCase__) or config.num_hidden_layers ) A__ = getattr(UpperCAmelCase__ , '''num_kv_heads''' , config.num_attention_heads) A__ = getattr(UpperCAmelCase__ , '''d_model''' , config.hidden_size) A__ = embed_dim // num_attention_heads A__ = outputs['''past_key_values'''] self.assertEqual(len(UpperCAmelCase__) , UpperCAmelCase__) A__ , A__ = inputs['''input_ids'''].shape for i in range(UpperCAmelCase__): if config.new_decoder_architecture: A__ = config.num_attention_heads elif config.multi_query: A__ = 1 self.assertEqual(len(past_kv[0]) , 2) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim)) self.assertEqual( past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim)) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Union[str, Any]: '''simple docstring''' A__ = AutoTokenizer.from_pretrained('''Rocketknight1/falcon-rw-1b''') A__ = FalconForCausalLM.from_pretrained('''Rocketknight1/falcon-rw-1b''') model.eval() model.to(UpperCAmelCase__) A__ = tokenizer('''My favorite food is''' , return_tensors='''pt''').to(UpperCAmelCase__) A__ = ( '''My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.''' ) A__ = model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=19) A__ = tokenizer.batch_decode(UpperCAmelCase__)[0] self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__) @slow def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[Any]: '''simple docstring''' for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: A__ = AutoTokenizer.from_pretrained(UpperCAmelCase__) A__ = FalconForCausalLM.from_pretrained(UpperCAmelCase__) model.eval() model.to(UpperCAmelCase__) A__ = tokenizer('''My favorite food is''' , return_tensors='''pt''').to(UpperCAmelCase__) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=4) model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=4) model.generate(**UpperCAmelCase__ , num_beams=2 , max_new_tokens=4) @slow def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: A__ = AutoTokenizer.from_pretrained(UpperCAmelCase__) A__ = FalconForCausalLM.from_pretrained(UpperCAmelCase__) model.eval() model.to(device=UpperCAmelCase__) A__ = tokenizer('''My favorite food is''' , return_tensors='''pt''').to(UpperCAmelCase__) # Test results are the same with and without cache A__ = model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=20 , use_cache=UpperCAmelCase__) A__ = model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=20 , use_cache=UpperCAmelCase__) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0)
87
import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None ) -> Dict: """simple docstring""" if "." in tensor_name: A__ = tensor_name.split('''.''' ) for split in splits[:-1]: A__ = getattr(lowercase_ , lowercase_ ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) A__ = new_module A__ = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f"""{module} does not have a parameter or a buffer named {tensor_name}.""" ) A__ = tensor_name in module._buffers A__ = getattr(lowercase_ , lowercase_ ) if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None: raise ValueError(f"""{tensor_name} is on the meta device, we need a `value` to put in on {device}.""" ) A__ = False A__ = False if is_buffer or not is_bitsandbytes_available(): A__ = False A__ = False else: A__ = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) A__ = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: A__ = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to('''cpu''' ) if value.dtype == torch.inta: A__ = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse( '''0.37.2''' ) if not is_abit_serializable: raise ValueError( '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ''' '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' ) else: A__ = torch.tensor(lowercase_ , device='''cpu''' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , lowercase_ ) and fpaa_statistics is None: A__ = new_value.T A__ = old_value.__dict__ if is_abit: A__ = bnb.nn.IntaParams(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) elif is_abit: A__ = bnb.nn.Paramsabit(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) A__ = new_value if fpaa_statistics is not None: setattr(module.weight , '''SCB''' , fpaa_statistics.to(lowercase_ ) ) else: if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to(lowercase_ ) else: A__ = torch.tensor(lowercase_ , device=lowercase_ ) if is_buffer: A__ = new_value else: A__ = nn.Parameter(lowercase_ , requires_grad=old_value.requires_grad ) A__ = new_value def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=False ) -> Dict: """simple docstring""" for name, module in model.named_children(): if current_key_name is None: A__ = [] current_key_name.append(lowercase_ ) if (isinstance(lowercase_ , nn.Linear ) or isinstance(lowercase_ , lowercase_ )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '''.'''.join(lowercase_ ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(lowercase_ , lowercase_ ): A__ , A__ = module.weight.shape else: A__ = module.in_features A__ = module.out_features if quantization_config.quantization_method() == "llm_int8": A__ = bnb.nn.LinearabitLt( lowercase_ , lowercase_ , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) A__ = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: A__ = bnb.nn.Linearabit( lowercase_ , lowercase_ , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) A__ = True # Store the module class in case we need to transpose the weight later A__ = type(lowercase_ ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(lowercase_ ) if len(list(module.children() ) ) > 0: A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ , has_been_replaced=lowercase_ , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None ) -> Tuple: """simple docstring""" A__ = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Dict: """simple docstring""" warnings.warn( '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , lowercase_ , ) return replace_with_bnb_linear(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Optional[Any]: """simple docstring""" warnings.warn( '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , lowercase_ , ) return set_module_quantized_tensor_to_device(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: """simple docstring""" A__ = deepcopy(lowercase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() A__ = find_tied_parameters(lowercase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowercase_ , lowercase_ ): A__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: A__ = sum(lowercase_ , [] ) A__ = len(lowercase_ ) > 0 # Check if it is a base model A__ = not hasattr(lowercase_ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head A__ = list(model.named_children() ) A__ = [list_modules[-1][0]] # add last module together with tied weights A__ = set(lowercase_ ) - set(lowercase_ ) A__ = list(set(lowercase_ ) ) + list(lowercase_ ) # remove ".weight" from the keys A__ = ['''.weight''', '''.bias'''] A__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: A__ = name.replace(lowercase_ , '''''' ) filtered_module_names.append(lowercase_ ) return filtered_module_names
87
1
'''simple docstring''' from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def A_ ( snake_case , snake_case , snake_case ): if not arr: return None, None, 0 if low == high: return low, high, arr[low] SCREAMING_SNAKE_CASE:Tuple = (low + high) // 2 SCREAMING_SNAKE_CASE:Dict = max_subarray(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE:Optional[int] = max_subarray(_lowerCamelCase , mid + 1 , _lowerCamelCase ) SCREAMING_SNAKE_CASE:Dict = max_cross_sum(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def A_ ( snake_case , snake_case , snake_case , snake_case ): SCREAMING_SNAKE_CASE:Union[str, Any] = float("-inf" ), -1 SCREAMING_SNAKE_CASE:Optional[int] = float("-inf" ), -1 SCREAMING_SNAKE_CASE:int | float = 0 for i in range(_lowerCamelCase , low - 1 , -1 ): summ += arr[i] if summ > left_sum: SCREAMING_SNAKE_CASE:Tuple = summ SCREAMING_SNAKE_CASE:Optional[int] = i SCREAMING_SNAKE_CASE:Union[str, Any] = 0 for i in range(mid + 1 , high + 1 ): summ += arr[i] if summ > right_sum: SCREAMING_SNAKE_CASE:Union[str, Any] = summ SCREAMING_SNAKE_CASE:Optional[int] = i return max_left, max_right, (left_sum + right_sum) def A_ ( snake_case ): SCREAMING_SNAKE_CASE:Tuple = [randint(1 , _lowerCamelCase ) for _ in range(_lowerCamelCase )] SCREAMING_SNAKE_CASE:Optional[Any] = time.time() max_subarray(_lowerCamelCase , 0 , input_size - 1 ) SCREAMING_SNAKE_CASE:Any = time.time() return end - start def A_ ( ): SCREAMING_SNAKE_CASE:Dict = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] SCREAMING_SNAKE_CASE:Union[str, Any] = [time_max_subarray(_lowerCamelCase ) for input_size in input_sizes] print("No of Inputs\t\tTime Taken" ) for input_size, runtime in zip(_lowerCamelCase , _lowerCamelCase ): print(_lowerCamelCase , "\t\t" , _lowerCamelCase ) plt.plot(_lowerCamelCase , _lowerCamelCase ) plt.xlabel("Number of Inputs" ) plt.ylabel("Time taken in seconds" ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
706
'''simple docstring''' from ....utils import logging A_ = logging.get_logger(__name__) class _snake_case ( _a ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=None ,SCREAMING_SNAKE_CASE__ : Optional[int]=2_048 ): SCREAMING_SNAKE_CASE:int = config.__dict__ SCREAMING_SNAKE_CASE:List[str] = modal_hidden_size if num_labels: SCREAMING_SNAKE_CASE:str = num_labels
465
0
"""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 __UpperCAmelCase = 'python tqdm regex requests packaging filelock numpy tokenizers'.split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append('dataclasses') if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append('importlib_metadata') for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(F"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py") def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase=None ): '''simple docstring''' require_version(deps[pkg] , __UpperCamelCase )
65
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class UpperCAmelCase__ ( __lowerCamelCase ): """simple docstring""" lowerCAmelCase__ : Any = ( """This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.""" """It takes two arguments named `image` which should be the original image, and `label` which should be a text """ """describing the elements what should be identified in the segmentation mask. The tool returns the mask.""" ) lowerCAmelCase__ : Tuple = """CIDAS/clipseg-rd64-refined""" lowerCAmelCase__ : Optional[Any] = """image_segmenter""" lowerCAmelCase__ : Optional[Any] = CLIPSegForImageSegmentation lowerCAmelCase__ : Any = ["""image""", """text"""] lowerCAmelCase__ : Optional[Any] = ["""image"""] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Tuple: requires_backends(self , ["vision"] ) super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: return self.pre_processor(text=[label] , images=[image] , padding=_SCREAMING_SNAKE_CASE , return_tensors="pt" ) def A ( self , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: with torch.no_grad(): a_ : List[Any] = self.model(**_SCREAMING_SNAKE_CASE ).logits return logits def A ( self , _SCREAMING_SNAKE_CASE ) -> List[Any]: a_ : List[Any] = outputs.cpu().detach().numpy() a_ : Optional[Any] = 0 a_ : Optional[int] = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
473
0
"""simple docstring""" import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowercase__ ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[Any] ) -> str: '''simple docstring''' if openai_config_file == "": a__ : int = OpenAIGPTConfig() else: a__ : str = OpenAIGPTConfig.from_json_file(snake_case__ ) a__ : int = OpenAIGPTModel(snake_case__ ) # Load weights from numpy load_tf_weights_in_openai_gpt(snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model a__ : Any = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME a__ : List[str] = pytorch_dump_folder_path + """/""" + CONFIG_NAME print(F"Save PyTorch model to {pytorch_weights_dump_path}" ) torch.save(model.state_dict() , snake_case__ ) print(F"Save configuration file to {pytorch_config_dump_path}" ) with open(snake_case__ , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--openai_checkpoint_folder_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--openai_config_file''', default='''''', type=str, help=( '''An optional config json file corresponding to the pre-trained OpenAI model. \n''' '''This specifies the model architecture.''' ), ) __UpperCAmelCase = parser.parse_args() convert_openai_checkpoint_to_pytorch( args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path )
706
"""simple docstring""" from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class __UpperCAmelCase : def __init__( self : Any , a_ : int , a_ : Any=13 , a_ : int=30 , a_ : int=2 , a_ : str=3 , a_ : List[Any]=True , a_ : Union[str, Any]=True , a_ : Any=32 , a_ : Union[str, Any]=2 , a_ : Union[str, Any]=4 , a_ : Optional[int]=37 , a_ : Any="gelu" , a_ : Optional[Any]=0.1 , a_ : str=0.1 , a_ : str=10 , a_ : str=0.02 , a_ : Dict=3 , a_ : Optional[Any]=None , a_ : str=2 , ) -> List[Any]: '''simple docstring''' a__ : Optional[Any] = parent a__ : Optional[int] = batch_size a__ : int = image_size a__ : Optional[Any] = patch_size a__ : List[Any] = num_channels a__ : List[str] = is_training a__ : List[Any] = use_labels a__ : List[Any] = hidden_size a__ : Tuple = num_hidden_layers a__ : Dict = num_attention_heads a__ : str = intermediate_size a__ : Union[str, Any] = hidden_act a__ : List[str] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Optional[int] = type_sequence_label_size a__ : Optional[Any] = initializer_range a__ : Any = scope a__ : List[str] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) a__ : Any = (image_size // patch_size) ** 2 a__ : List[str] = num_patches + 2 def UpperCAmelCase ( self : Any ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a__ : List[str] = None if self.use_labels: a__ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : int = self.get_config() return config, pixel_values, labels def UpperCAmelCase ( self : Dict ) -> int: '''simple docstring''' return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def UpperCAmelCase ( self : Any , a_ : Dict , a_ : Optional[Any] , a_ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ : int = TFDeiTModel(config=a_ ) a__ : List[str] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self : Any , a_ : int , a_ : Tuple , a_ : Union[str, Any] ) -> Dict: '''simple docstring''' a__ : Dict = TFDeiTForMaskedImageModeling(config=a_ ) a__ : str = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images a__ : List[Any] = 1 a__ : int = TFDeiTForMaskedImageModeling(a_ ) a__ : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) a__ : Any = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def UpperCAmelCase ( self : List[str] , a_ : List[str] , a_ : str , a_ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : Any = self.type_sequence_label_size a__ : Union[str, Any] = TFDeiTForImageClassification(a_ ) a__ : List[str] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images a__ : Union[str, Any] = 1 a__ : Any = TFDeiTForImageClassification(a_ ) a__ : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) a__ : int = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase ( self : str ) -> str: '''simple docstring''' a__ : List[Any] = self.prepare_config_and_inputs() a__ , a__ , a__ : Optional[Any] = config_and_inputs a__ : Any = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class __UpperCAmelCase ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): __lowerCamelCase : Union[str, Any] = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) __lowerCamelCase : Dict = ( { "feature-extraction": TFDeiTModel, "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) __lowerCamelCase : Any = False __lowerCamelCase : Dict = False __lowerCamelCase : int = False __lowerCamelCase : Optional[Any] = False def UpperCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' a__ : int = TFDeiTModelTester(self ) a__ : str = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def UpperCAmelCase ( self : int ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def UpperCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' pass def UpperCAmelCase ( self : Any ) -> Union[str, Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Optional[Any] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) a__ : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , tf.keras.layers.Dense ) ) def UpperCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' a__ , a__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Dict = model_class(a_ ) a__ : Any = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Dict = [*signature.parameters.keys()] a__ : List[str] = ["pixel_values"] self.assertListEqual(arg_names[:1] , a_ ) def UpperCAmelCase ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def UpperCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' a__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def UpperCAmelCase ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def UpperCAmelCase ( self : List[Any] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any]=False ) -> Dict: '''simple docstring''' a__ : int = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def UpperCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Tuple = TFDeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def lowercase__ ( ) -> Optional[int]: '''simple docstring''' a__ : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class __UpperCAmelCase ( unittest.TestCase ): @cached_property def UpperCAmelCase ( self : Any ) -> Tuple: '''simple docstring''' return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def UpperCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' a__ : Tuple = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ) a__ : Optional[Any] = self.default_image_processor a__ : Optional[Any] = prepare_img() a__ : Tuple = image_processor(images=a_ , return_tensors="tf" ) # forward pass a__ : int = model(**a_ ) # verify the logits a__ : int = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , a_ ) a__ : Union[str, Any] = tf.constant([-1.0266, 0.1912, -1.2861] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , a_ , atol=1E-4 ) )
251
0
'''simple docstring''' from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' __lowercase : Any = '''EncodecFeatureExtractor''' __lowercase : int = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase ) -> str: super().__init__(__UpperCAmelCase ,__UpperCAmelCase ) lowerCAmelCase__ : Tuple = self.feature_extractor lowerCAmelCase__ : Tuple = False def UpperCAmelCase_ ( self ,__UpperCAmelCase=None ,__UpperCAmelCase=None ,__UpperCAmelCase=True ) -> List[str]: return self.tokenizer.get_decoder_prompt_ids(task=__UpperCAmelCase ,language=__UpperCAmelCase ,no_timestamps=__UpperCAmelCase ) def __call__( self ,*__UpperCAmelCase ,**__UpperCAmelCase ) -> str: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*__UpperCAmelCase ,**__UpperCAmelCase ) lowerCAmelCase__ : Optional[Any] = kwargs.pop("""audio""" ,__UpperCAmelCase ) lowerCAmelCase__ : Dict = kwargs.pop("""sampling_rate""" ,__UpperCAmelCase ) lowerCAmelCase__ : Tuple = kwargs.pop("""text""" ,__UpperCAmelCase ) if len(__UpperCAmelCase ) > 0: lowerCAmelCase__ : Optional[int] = args[0] lowerCAmelCase__ : List[Any] = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: lowerCAmelCase__ : Optional[Any] = self.tokenizer(__UpperCAmelCase ,**__UpperCAmelCase ) if audio is not None: lowerCAmelCase__ : Any = self.feature_extractor(__UpperCAmelCase ,*__UpperCAmelCase ,sampling_rate=__UpperCAmelCase ,**__UpperCAmelCase ) if audio is None: return inputs elif text is None: return audio_inputs else: lowerCAmelCase__ : List[str] = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: lowerCAmelCase__ : int = audio_inputs["""padding_mask"""] return inputs def UpperCAmelCase_ ( self ,*__UpperCAmelCase ,**__UpperCAmelCase ) -> List[str]: lowerCAmelCase__ : Union[str, Any] = kwargs.pop("""audio""" ,__UpperCAmelCase ) lowerCAmelCase__ : str = kwargs.pop("""padding_mask""" ,__UpperCAmelCase ) if len(__UpperCAmelCase ) > 0: lowerCAmelCase__ : Union[str, Any] = args[0] lowerCAmelCase__ : Dict = args[1:] if audio_values is not None: return self._decode_audio(__UpperCAmelCase ,padding_mask=__UpperCAmelCase ) else: return self.tokenizer.batch_decode(*__UpperCAmelCase ,**__UpperCAmelCase ) def UpperCAmelCase_ ( self ,*__UpperCAmelCase ,**__UpperCAmelCase ) -> Any: return self.tokenizer.decode(*__UpperCAmelCase ,**__UpperCAmelCase ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase = None ) -> List[np.ndarray]: lowerCAmelCase__ : Optional[Any] = to_numpy(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : int = audio_values.shape if padding_mask is None: return list(__UpperCAmelCase ) lowerCAmelCase__ : Tuple = to_numpy(__UpperCAmelCase ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) lowerCAmelCase__ : Optional[int] = seq_len - padding_mask.shape[-1] lowerCAmelCase__ : Tuple = 1 - self.feature_extractor.padding_value lowerCAmelCase__ : int = np.pad(__UpperCAmelCase ,((0, 0), (0, difference)) ,"""constant""" ,constant_values=__UpperCAmelCase ) lowerCAmelCase__ : int = audio_values.tolist() for i in range(__UpperCAmelCase ): lowerCAmelCase__ : List[str] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] lowerCAmelCase__ : List[Any] = sliced_audio.reshape(__UpperCAmelCase ,-1 ) return audio_values
565
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
565
1
"""simple docstring""" from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class __lowerCamelCase ( _a ): def __init__( self , snake_case_ , snake_case_ = None , snake_case_ = None , snake_case_ = True , snake_case_ = None , snake_case_ = False , snake_case_ = None , snake_case_ = True , snake_case_ = "arrow" , **snake_case_ , ) -> str: super().__init__( split=snake_case_ , features=snake_case_ , cache_dir=snake_case_ , keep_in_memory=snake_case_ , streaming=snake_case_ , **snake_case_ , ) UpperCamelCase__ = load_from_cache_file UpperCamelCase__ = file_format UpperCamelCase__ = Spark( df=snake_case_ , features=snake_case_ , cache_dir=snake_case_ , working_dir=snake_case_ , **snake_case_ , ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) UpperCamelCase__ = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=snake_case_ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
20
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __lowerCamelCase ( _a ): @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' , type=snake_case_ , default=snake_case_ , help='Path to location to store the models' ) download_parser.add_argument( '--force' , action='store_true' , help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' , action='store_true' , help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' , ) download_parser.add_argument('model' , type=snake_case_ , help='Name of the model to download' ) download_parser.set_defaults(func=snake_case_ ) def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = model UpperCamelCase__ = cache UpperCamelCase__ = force UpperCamelCase__ = trust_remote_code def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
20
1
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> str: lowercase__ = [] for line in lines: lowercase__ = re.sub(R'#.*' , '' , _SCREAMING_SNAKE_CASE ) # remove comments if line: filtered_lines.append(_SCREAMING_SNAKE_CASE ) lowercase__ = '\n'.join(_SCREAMING_SNAKE_CASE ) # Make a hash from all this code lowercase__ = full_str.encode('utf-8' ) return shaaaa(_SCREAMING_SNAKE_CASE ).hexdigest() # get importable module names and hash for caching lowercase_ = { """csv""": (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), """json""": (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), """pandas""": (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), """parquet""": (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), """arrow""": (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), """text""": (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), """imagefolder""": (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), """audiofolder""": (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions lowercase_ = { """.csv""": ("""csv""", {}), """.tsv""": ("""csv""", {"""sep""": """\t"""}), """.json""": ("""json""", {}), """.jsonl""": ("""json""", {}), """.parquet""": ("""parquet""", {}), """.arrow""": ("""arrow""", {}), """.txt""": ("""text""", {}), } _EXTENSION_TO_MODULE.update({ext: ("""imagefolder""", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("""imagefolder""", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ("""audiofolder""", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("""audiofolder""", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) lowercase_ = {"""imagefolder""", """audiofolder"""} # Used to filter data files based on extensions given a module name lowercase_ = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append(""".zip""") _MODULE_TO_EXTENSIONS["audiofolder"].append(""".zip""")
235
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class SCREAMING_SNAKE_CASE (unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> Tuple: """simple docstring""" lowercase__ = inspect.getfile(accelerate.test_utils ) lowercase__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 lowercase__ = test_metrics @require_cpu def SCREAMING_SNAKE_CASE_ ( self : List[Any] )-> Dict: """simple docstring""" debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" debug_launcher(self.test_metrics.main ) @require_single_gpu def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.test_metrics.main() @require_multi_gpu def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> List[Any]: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices.""" ) lowercase__ = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(a , env=os.environ.copy() )
235
1
"""simple docstring""" import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType _A : int = False, False, False @dataclass class a__ : '''simple docstring''' __lowerCAmelCase = None __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = None # Automatically constructed __lowerCAmelCase = """dict""" __lowerCAmelCase = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()} ) __lowerCAmelCase = field(default="""Audio""", init=a_, repr=a_ ) def __call__( self ): return self.pa_type def __magic_name__ ( self , _a ): try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("To support encoding audio data, please install 'soundfile'." ) from err if isinstance(_a , _a ): return {"bytes": None, "path": value} elif isinstance(_a , _a ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes lowercase : Tuple = BytesIO() sf.write(_a , value["array"] , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("pcm" ): # "PCM" only has raw audio bytes if value.get("sampling_rate" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("To use PCM files, please specify a 'sampling_rate' in Audio object" ) if value.get("bytes" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) lowercase : Optional[int] = np.frombuffer(value["bytes"] , dtype=np.intaa ).astype(np.floataa ) / 32_767 else: lowercase : Optional[Any] = np.memmap(value["path"] , dtype="h" , mode="r" ).astype(np.floataa ) / 32_767 lowercase : List[str] = BytesIO(bytes() ) sf.write(_a , _a , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def __magic_name__ ( self , _a , _a = None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Audio(decode=True) instead." ) lowercase : Optional[int] = (value["path"], BytesIO(value["bytes"] )) if value["bytes"] is not None else (value["path"], None) if path is None and file is None: raise ValueError(f"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("To support decoding audio files, please install 'librosa' and 'soundfile'." ) from err lowercase : Optional[int] = xsplitext(_a )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( "Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( "Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) if file is None: lowercase : Union[str, Any] = token_per_repo_id or {} lowercase : Dict = path.split("::" )[-1] try: lowercase : Optional[int] = string_to_dict(_a , config.HUB_DATASETS_URL )["repo_id"] lowercase : Union[str, Any] = token_per_repo_id[repo_id] except (ValueError, KeyError): lowercase : List[Any] = None with xopen(_a , "rb" , use_auth_token=_a ) as f: lowercase : int = sf.read(_a ) else: lowercase : Any = sf.read(_a ) lowercase : List[Any] = array.T if self.mono: lowercase : List[Any] = librosa.to_mono(_a ) if self.sampling_rate and self.sampling_rate != sampling_rate: lowercase : Union[str, Any] = librosa.resample(_a , orig_sr=_a , target_sr=self.sampling_rate ) lowercase : List[str] = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def __magic_name__ ( self ): from .features import Value if self.decode: raise ValueError("Cannot flatten a decoded Audio feature." ) return { "bytes": Value("binary" ), "path": Value("string" ), } def __magic_name__ ( self , _a ): if pa.types.is_string(storage.type ): lowercase : List[Any] = pa.array([None] * len(_a ) , type=pa.binary() ) lowercase : Any = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): lowercase : List[str] = pa.array([None] * len(_a ) , type=pa.string() ) lowercase : List[Any] = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("array" ): lowercase : str = pa.array([Audio().encode_example(_a ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: lowercase : Optional[Any] = storage.field("bytes" ) else: lowercase : Optional[Any] = pa.array([None] * len(_a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: lowercase : Dict = storage.field("path" ) else: lowercase : List[Any] = pa.array([None] * len(_a ) , type=pa.string() ) lowercase : Tuple = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) return array_cast(_a , self.pa_type ) def __magic_name__ ( self , _a ): @no_op_if_value_is_null def path_to_bytes(_a ): with xopen(_a , "rb" ) as f: lowercase : List[str] = f.read() return bytes_ lowercase : Dict = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) lowercase : int = pa.array( [os.path.basename(_a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) lowercase : Dict = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(_a , self.pa_type )
716
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class a__ ( unittest.TestCase ): @slow def __magic_name__ ( self ): lowercase : List[str] = AutoImageProcessor.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" ) lowercase : Any = AutoModelForImageClassification.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" ) model.to(_a ) from datasets import load_dataset lowercase : Any = load_dataset("nielsr/rvlcdip-demo" ) lowercase : List[str] = dataset["train"][0]["image"].convert("RGB" ) lowercase : str = image_processor(_a , return_tensors="pt" ).to(_a ) # forward pass with torch.no_grad(): lowercase : Tuple = model(**_a ) lowercase : Dict = outputs.logits lowercase : Union[str, Any] = torch.Size((1, 16) ) self.assertEqual(logits.shape , _a ) lowercase : int = torch.tensor( [-0.4_1_5_8, -0.4_0_9_2, -0.4_3_4_7] , device=_a , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , _a , atol=1E-4 ) )
518
0
from collections.abc import Iterable from typing import Any class snake_case_ : '''simple docstring''' def __init__( self, A_ = None ) -> Union[str, Any]: UpperCAmelCase__ =value UpperCAmelCase__ =None # Added in order to delete a node easier UpperCAmelCase__ =None UpperCAmelCase__ =None def __repr__( self ) -> Any: from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({f"""{self.value}""": (self.left, self.right)}, indent=1 ) class snake_case_ : '''simple docstring''' def __init__( self, A_ = None ) -> Optional[Any]: UpperCAmelCase__ =root def __str__( self ) -> Optional[int]: return str(self.root ) def __UpperCAmelCase ( self, A_, A_ ) -> List[str]: if new_children is not None: # reset its kids UpperCAmelCase__ =node.parent if node.parent is not None: # reset its parent if self.is_right(_UpperCamelCase ): # If it is the right children UpperCAmelCase__ =new_children else: UpperCAmelCase__ =new_children else: UpperCAmelCase__ =new_children def __UpperCAmelCase ( self, A_ ) -> Union[str, Any]: if node.parent and node.parent.right: return node == node.parent.right return False def __UpperCAmelCase ( self ) -> List[Any]: return self.root is None def __UpperCAmelCase ( self, A_ ) -> Union[str, Any]: UpperCAmelCase__ =Node(_UpperCamelCase ) # create a new Node if self.empty(): # if Tree is empty UpperCAmelCase__ =new_node # set its root else: # Tree is not empty UpperCAmelCase__ =self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: UpperCAmelCase__ =new_node # We insert the new node in a leaf break else: UpperCAmelCase__ =parent_node.left else: if parent_node.right is None: UpperCAmelCase__ =new_node break else: UpperCAmelCase__ =parent_node.right UpperCAmelCase__ =parent_node def __UpperCAmelCase ( self, *A_ ) -> List[str]: for value in values: self.__insert(_UpperCamelCase ) def __UpperCAmelCase ( self, A_ ) -> int: if self.empty(): raise IndexError("Warning: Tree is empty! please use another." ) else: UpperCAmelCase__ =self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: UpperCAmelCase__ =node.left if value < node.value else node.right return node def __UpperCAmelCase ( self, A_ = None ) -> Optional[Any]: if node is None: if self.root is None: return None UpperCAmelCase__ =self.root if not self.empty(): while node.right is not None: UpperCAmelCase__ =node.right return node def __UpperCAmelCase ( self, A_ = None ) -> List[Any]: if node is None: UpperCAmelCase__ =self.root if self.root is None: return None if not self.empty(): UpperCAmelCase__ =self.root while node.left is not None: UpperCAmelCase__ =node.left return node def __UpperCAmelCase ( self, A_ ) -> Optional[Any]: UpperCAmelCase__ =self.search(_UpperCamelCase ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(_UpperCamelCase, _UpperCamelCase ) elif node.left is None: # Has only right children self.__reassign_nodes(_UpperCamelCase, node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(_UpperCamelCase, node.left ) else: UpperCAmelCase__ =self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore UpperCAmelCase__ =( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def __UpperCAmelCase ( self, A_ ) -> Union[str, Any]: if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def __UpperCAmelCase ( self, A_=None ) -> List[str]: if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def __UpperCAmelCase ( self, A_, A_ ) -> str: if node: self.inorder(_UpperCamelCase, node.left ) arr.append(node.value ) self.inorder(_UpperCamelCase, node.right ) def __UpperCAmelCase ( self, A_, A_ ) -> Tuple: UpperCAmelCase__ =[] self.inorder(_UpperCamelCase, _UpperCamelCase ) # append all values to list using inorder traversal return arr[k - 1] def _UpperCAmelCase ( A ): '''simple docstring''' UpperCAmelCase__ =[] if curr_node is not None: UpperCAmelCase__ =postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def _UpperCAmelCase ( ): '''simple docstring''' UpperCAmelCase__ =(8, 3, 6, 1, 10, 14, 13, 4, 7) UpperCAmelCase__ =BinarySearchTree() for i in testlist: t.insert(SCREAMING_SNAKE_CASE_ ) # Prints all the elements of the list in order traversal print(SCREAMING_SNAKE_CASE_ ) if t.search(6 ) is not None: print("The value 6 exists" ) else: print("The value 6 doesn\'t exist" ) if t.search(-1 ) is not None: print("The value -1 exists" ) else: print("The value -1 doesn\'t exist" ) if not t.empty(): print("Max Value: " , t.get_max().value ) # type: ignore print("Min Value: " , t.get_min().value ) # type: ignore for i in testlist: t.remove(SCREAMING_SNAKE_CASE_ ) print(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
625
from __future__ import annotations def A__ ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" _UpperCAmelCase = str(SCREAMING_SNAKE_CASE_ ) return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set('''123456789''' ) def A__ ( ) -> int | None: """simple docstring""" for base_num in range(99_99 , 49_99 , -1 ): _UpperCAmelCase = 10_00_02 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate for base_num in range(3_33 , 99 , -1 ): _UpperCAmelCase = 1_00_20_03 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate return None if __name__ == "__main__": print(f'''{solution() = }''')
32
0
import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { """artists_file""": """artists.json""", """lyrics_file""": """lyrics.json""", """genres_file""": """genres.json""", } UpperCamelCase = { """artists_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json""", }, """genres_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json""", }, """lyrics_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json""", }, } UpperCamelCase = { """jukebox""": 512, } class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" snake_case = VOCAB_FILES_NAMES snake_case = PRETRAINED_VOCAB_FILES_MAP snake_case = PRETRAINED_LYRIC_TOKENS_SIZES snake_case = ["input_ids", "attention_mask"] def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=["v3", "v2", "v2"] , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE="<|endoftext|>" , **_SCREAMING_SNAKE_CASE , )->Any: '''simple docstring''' A_ : Union[str, Any] = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else unk_token super().__init__( unk_token=_SCREAMING_SNAKE_CASE , n_genres=_SCREAMING_SNAKE_CASE , version=_SCREAMING_SNAKE_CASE , max_n_lyric_tokens=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) A_ : List[str] = version A_ : str = max_n_lyric_tokens A_ : Optional[int] = n_genres with open(_SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as vocab_handle: A_ : Any = json.load(_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as vocab_handle: A_ : Union[str, Any] = json.load(_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as vocab_handle: A_ : Tuple = json.load(_SCREAMING_SNAKE_CASE ) A_ : str = R'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 79: A_ : Any = oov.replace(R'''\-\'''' , R'''\-+\'''' ) A_ : List[Any] = regex.compile(_SCREAMING_SNAKE_CASE ) A_ : Any = {v: k for k, v in self.artists_encoder.items()} A_ : List[Any] = {v: k for k, v in self.genres_encoder.items()} A_ : Tuple = {v: k for k, v in self.lyrics_encoder.items()} @property def _snake_case ( self )->str: '''simple docstring''' return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def _snake_case ( self )->str: '''simple docstring''' return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )->Tuple: '''simple docstring''' A_ : List[str] = [self.artists_encoder.get(_SCREAMING_SNAKE_CASE , 0 ) for artist in list_artists] for genres in range(len(_SCREAMING_SNAKE_CASE ) ): A_ : Any = [self.genres_encoder.get(_SCREAMING_SNAKE_CASE , 0 ) for genre in list_genres[genres]] A_ : Tuple = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) A_ : int = [[self.lyrics_encoder.get(_SCREAMING_SNAKE_CASE , 0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def _snake_case ( self , _SCREAMING_SNAKE_CASE )->Dict: '''simple docstring''' return list(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )->Dict: '''simple docstring''' A_ , A_ , A_ : int = self.prepare_for_tokenization(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : List[Any] = self._tokenize(_SCREAMING_SNAKE_CASE ) return artist, genre, lyrics def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False )->Tuple[str, str, str, Dict[str, Any]]: '''simple docstring''' for idx in range(len(self.version ) ): if self.version[idx] == "v3": A_ : Tuple = artists[idx].lower() A_ : int = [genres[idx].lower()] else: A_ : Tuple = self._normalize(artists[idx] ) + '''.v2''' A_ : int = [ self._normalize(_SCREAMING_SNAKE_CASE ) + '''.v2''' for genre in genres[idx].split('''_''' ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": A_ : Optional[int] = regex.compile(R'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' ) A_ : Tuple = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n''' A_ : str = {vocab[index]: index + 1 for index in range(len(_SCREAMING_SNAKE_CASE ) )} A_ : Optional[int] = 0 A_ : Tuple = len(_SCREAMING_SNAKE_CASE ) + 1 A_ : List[Any] = self.vocab A_ : Dict = {v: k for k, v in self.vocab.items()} A_ : Dict = '''''' else: A_ : Optional[Any] = regex.compile(R'''[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+''' ) A_ : List[Any] = self._run_strip_accents(_SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = lyrics.replace('''\\''' , '''\n''' ) A_ : Dict = self.out_of_vocab.sub('''''' , _SCREAMING_SNAKE_CASE ), [], [] return artists, genres, lyrics def _snake_case ( self , _SCREAMING_SNAKE_CASE )->Optional[int]: '''simple docstring''' A_ : Tuple = unicodedata.normalize('''NFD''' , _SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = [] for char in text: A_ : int = unicodedata.category(_SCREAMING_SNAKE_CASE ) if cat == "Mn": continue output.append(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )->str: '''simple docstring''' A_ : int = ( [chr(_SCREAMING_SNAKE_CASE ) for i in range(ord('''a''' ) , ord('''z''' ) + 1 )] + [chr(_SCREAMING_SNAKE_CASE ) for i in range(ord('''A''' ) , ord('''Z''' ) + 1 )] + [chr(_SCREAMING_SNAKE_CASE ) for i in range(ord('''0''' ) , ord('''9''' ) + 1 )] + ['''.'''] ) A_ : Optional[int] = frozenset(_SCREAMING_SNAKE_CASE ) A_ : int = re.compile(R'''_+''' ) A_ : str = ''''''.join([c if c in accepted else '''_''' for c in text.lower()] ) A_ : str = pattern.sub('''_''' , _SCREAMING_SNAKE_CASE ).strip('''_''' ) return text def _snake_case ( self , _SCREAMING_SNAKE_CASE )->str: '''simple docstring''' return " ".join(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )->int: '''simple docstring''' if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): A_ : Union[str, Any] = TensorType(_SCREAMING_SNAKE_CASE ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( '''Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.''' ) import tensorflow as tf A_ : List[Any] = tf.constant A_ : Union[str, Any] = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError('''Unable to convert output to PyTorch tensors format, PyTorch is not installed.''' ) import torch A_ : Any = torch.tensor A_ : List[str] = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError('''Unable to convert output to JAX tensors format, JAX is not installed.''' ) import jax.numpy as jnp # noqa: F811 A_ : List[str] = jnp.array A_ : Optional[int] = _is_jax else: A_ : Optional[Any] = np.asarray A_ : Union[str, Any] = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: A_ : Tuple = [inputs] if not is_tensor(_SCREAMING_SNAKE_CASE ): A_ : Union[str, Any] = as_tensor(_SCREAMING_SNAKE_CASE ) except: # noqa E722 raise ValueError( '''Unable to create tensor, you should probably activate truncation and/or padding ''' '''with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.''' ) return inputs def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE="pt" )->BatchEncoding: '''simple docstring''' A_ : Dict = [0, 0, 0] A_ : Dict = [artist] * len(self.version ) A_ : str = [genres] * len(self.version ) A_ , A_ , A_ : Union[str, Any] = self.tokenize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ , A_ , A_ : str = self._convert_token_to_id(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : Optional[int] = [-INFINITY] * len(full_tokens[-1] ) A_ : int = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=_SCREAMING_SNAKE_CASE ) for i in range(len(self.version ) ) ] return BatchEncoding({'''input_ids''': input_ids, '''attention_masks''': attention_masks} ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )->Tuple[str]: '''simple docstring''' if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return A_ : Dict = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''artists_file'''] ) with open(_SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.artists_encoder , ensure_ascii=_SCREAMING_SNAKE_CASE ) ) A_ : int = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''genres_file'''] ) with open(_SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.genres_encoder , ensure_ascii=_SCREAMING_SNAKE_CASE ) ) A_ : int = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''lyrics_file'''] ) with open(_SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.lyrics_encoder , ensure_ascii=_SCREAMING_SNAKE_CASE ) ) return (artists_file, genres_file, lyrics_file) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )->List[str]: '''simple docstring''' A_ : Union[str, Any] = self.artists_decoder.get(_SCREAMING_SNAKE_CASE ) A_ : Tuple = [self.genres_decoder.get(_SCREAMING_SNAKE_CASE ) for genre in genres_index] A_ : List[str] = [self.lyrics_decoder.get(_SCREAMING_SNAKE_CASE ) for character in lyric_index] return artist, genres, lyrics
152
from functools import reduce UpperCamelCase = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE = N ): return max( # mypy cannot properly interpret reduce int(reduce(lambda SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str(int(SCREAMING_SNAKE_CASE ) * int(SCREAMING_SNAKE_CASE ) ) , n[i : i + 13] ) ) for i in range(len(SCREAMING_SNAKE_CASE ) - 12 ) ) if __name__ == "__main__": print(F'''{solution() = }''')
152
1
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
14
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = KandinskyInpaintPipeline UpperCAmelCase__ : Optional[int] = ["prompt", "image_embeds", "negative_image_embeds", "image", "mask_image"] UpperCAmelCase__ : Optional[Any] = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", "mask_image", ] UpperCAmelCase__ : Optional[int] = [ "generator", "height", "width", "latents", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] UpperCAmelCase__ : Any = False @property def __lowercase ( self ) -> Optional[int]: return 3_2 @property def __lowercase ( self ) -> int: return 3_2 @property def __lowercase ( self ) -> List[str]: return self.time_input_dim @property def __lowercase ( self ) -> List[str]: return self.time_input_dim * 4 @property def __lowercase ( self ) -> Optional[Any]: return 1_0_0 @property def __lowercase ( self ) -> Optional[Any]: _a : Any = XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base''' ) return tokenizer @property def __lowercase ( self ) -> str: torch.manual_seed(0 ) _a : List[Any] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_0_0_5 , ) _a : Optional[int] = MultilingualCLIP(_a ) _a : Tuple = text_encoder.eval() return text_encoder @property def __lowercase ( self ) -> str: torch.manual_seed(0 ) _a : List[str] = { '''in_channels''': 9, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''text_image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''text_image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } _a : Dict = UNetaDConditionModel(**_a ) return model @property def __lowercase ( self ) -> Optional[int]: return { "block_out_channels": [3_2, 6_4], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __lowercase ( self ) -> Tuple: torch.manual_seed(0 ) _a : List[Any] = VQModel(**self.dummy_movq_kwargs ) return model def __lowercase ( self ) -> Any: _a : List[Any] = self.dummy_text_encoder _a : Optional[Any] = self.dummy_tokenizer _a : Optional[Any] = self.dummy_unet _a : Union[str, Any] = self.dummy_movq _a : Tuple = DDIMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''linear''' , beta_start=0.0_0085 , beta_end=0.012 , clip_sample=_a , set_alpha_to_one=_a , steps_offset=1 , prediction_type='''epsilon''' , thresholding=_a , ) _a : str = { '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __lowercase ( self , _a , _a=0 ) -> int: _a : Union[str, Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_a ) ).to(_a ) _a : List[str] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_a ) # create init_image _a : Tuple = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_a ) ).to(_a ) _a : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] _a : Optional[int] = Image.fromarray(np.uinta(_a ) ).convert('''RGB''' ).resize((2_5_6, 2_5_6) ) # create mask _a : Union[str, Any] = np.ones((6_4, 6_4) , dtype=np.floataa ) _a : List[str] = 0 if str(_a ).startswith('''mps''' ): _a : Tuple = torch.manual_seed(_a ) else: _a : Any = torch.Generator(device=_a ).manual_seed(_a ) _a : Any = { '''prompt''': '''horse''', '''image''': init_image, '''mask_image''': mask, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 6_4, '''width''': 6_4, '''num_inference_steps''': 2, '''guidance_scale''': 4.0, '''output_type''': '''np''', } return inputs def __lowercase ( self ) -> Optional[Any]: _a : Optional[Any] = '''cpu''' _a : List[Any] = self.get_dummy_components() _a : Tuple = self.pipeline_class(**_a ) _a : int = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _a : Any = pipe(**self.get_dummy_inputs(_a ) ) _a : str = output.images _a : Tuple = pipe( **self.get_dummy_inputs(_a ) , return_dict=_a , )[0] _a : Union[str, Any] = image[0, -3:, -3:, -1] _a : Tuple = image_from_tuple[0, -3:, -3:, -1] print(F"""image.shape {image.shape}""" ) assert image.shape == (1, 6_4, 6_4, 3) _a : str = np.array( [0.832_6919, 0.7379_0467, 0.2091_8581, 0.930_9612, 0.551_1791, 0.4371_3328, 0.551_3321, 0.4992_2934, 0.5949_7786] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" def __lowercase ( self ) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self ) -> Union[str, Any]: _a : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy''' ) _a : str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) _a : Tuple = np.ones((7_6_8, 7_6_8) , dtype=np.floataa ) _a : Any = 0 _a : Optional[Any] = '''a hat''' _a : Optional[Any] = KandinskyPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(_a ) _a : Tuple = KandinskyInpaintPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-inpaint''' , torch_dtype=torch.floataa ) _a : Union[str, Any] = pipeline.to(_a ) pipeline.set_progress_bar_config(disable=_a ) _a : Union[str, Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) _a , _a : Dict = pipe_prior( _a , generator=_a , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() _a : Optional[int] = pipeline( _a , image=_a , mask_image=_a , image_embeds=_a , negative_image_embeds=_a , generator=_a , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , output_type='''np''' , ) _a : Optional[int] = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_a , _a )
14
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCamelCase = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3FeatureExtractor'] _lowerCamelCase = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
613
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _lowerCamelCase = { 'configuration_roberta_prelayernorm': [ 'ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RobertaPreLayerNormConfig', 'RobertaPreLayerNormOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST', 'RobertaPreLayerNormForCausalLM', 'RobertaPreLayerNormForMaskedLM', 'RobertaPreLayerNormForMultipleChoice', 'RobertaPreLayerNormForQuestionAnswering', 'RobertaPreLayerNormForSequenceClassification', 'RobertaPreLayerNormForTokenClassification', 'RobertaPreLayerNormModel', 'RobertaPreLayerNormPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRobertaPreLayerNormForCausalLM', 'TFRobertaPreLayerNormForMaskedLM', 'TFRobertaPreLayerNormForMultipleChoice', 'TFRobertaPreLayerNormForQuestionAnswering', 'TFRobertaPreLayerNormForSequenceClassification', 'TFRobertaPreLayerNormForTokenClassification', 'TFRobertaPreLayerNormMainLayer', 'TFRobertaPreLayerNormModel', 'TFRobertaPreLayerNormPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'FlaxRobertaPreLayerNormForCausalLM', 'FlaxRobertaPreLayerNormForMaskedLM', 'FlaxRobertaPreLayerNormForMultipleChoice', 'FlaxRobertaPreLayerNormForQuestionAnswering', 'FlaxRobertaPreLayerNormForSequenceClassification', 'FlaxRobertaPreLayerNormForTokenClassification', 'FlaxRobertaPreLayerNormModel', 'FlaxRobertaPreLayerNormPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
613
1
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() snake_case__ : Any = logging.get_logger(__name__) def __lowerCamelCase ( A__ : int , A__ : List[str]=False ) -> Optional[Any]: lowerCamelCase_ : List[Any] = [] # fmt: off # stem: rename_keys.append(("""cls_token""", """vit.embeddings.cls_token""") ) rename_keys.append(("""pos_embed""", """vit.embeddings.position_embeddings""") ) rename_keys.append(("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias""") ) # backbone rename_keys.append(("""patch_embed.backbone.stem.conv.weight""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight""") ) rename_keys.append(("""patch_embed.backbone.stem.norm.weight""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight""") ) rename_keys.append(("""patch_embed.backbone.stem.norm.bias""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias""") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias''') ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((f'''blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''') ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" lowerCamelCase_ : List[Any] = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) # fmt: on return rename_keys def __lowerCamelCase ( A__ : Tuple , A__ : str , A__ : Any=False ) -> str: for i in range(config.num_hidden_layers ): if base_model: lowerCamelCase_ : List[Any] = """""" else: lowerCamelCase_ : List[str] = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCamelCase_ : Optional[int] = state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) lowerCamelCase_ : List[str] = state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict lowerCamelCase_ : List[str] = in_proj_weight[ : config.hidden_size, : ] lowerCamelCase_ : int = in_proj_bias[: config.hidden_size] lowerCamelCase_ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCamelCase_ : str = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCamelCase_ : Any = in_proj_weight[ -config.hidden_size :, : ] lowerCamelCase_ : List[str] = in_proj_bias[-config.hidden_size :] def __lowerCamelCase ( A__ : Tuple ) -> Optional[int]: lowerCamelCase_ : List[Any] = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(_lowerCAmelCase , _lowerCAmelCase ) def __lowerCamelCase ( A__ : Union[str, Any] , A__ : Optional[Any] , A__ : Optional[Any] ) -> str: lowerCamelCase_ : Optional[int] = dct.pop(_lowerCAmelCase ) lowerCamelCase_ : List[Any] = val def __lowerCamelCase ( ) -> Optional[int]: lowerCamelCase_ : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" lowerCamelCase_ : Optional[Any] = Image.open(requests.get(_lowerCAmelCase , stream=_lowerCAmelCase ).raw ) return im @torch.no_grad() def __lowerCamelCase ( A__ : Union[str, Any] , A__ : Tuple , A__ : Tuple=False ) -> int: lowerCamelCase_ : Tuple = BitConfig( global_padding="""same""" , layer_type="""bottleneck""" , depths=(3, 4, 9) , out_features=["""stage3"""] , embedding_dynamic_padding=_lowerCAmelCase , ) lowerCamelCase_ : Union[str, Any] = ViTHybridConfig(backbone_config=_lowerCAmelCase , image_size=384 , num_labels=1000 ) lowerCamelCase_ : Tuple = False # load original model from timm lowerCamelCase_ : int = timm.create_model(_lowerCAmelCase , pretrained=_lowerCAmelCase ) timm_model.eval() # load state_dict of original model, remove and rename some keys lowerCamelCase_ : Tuple = timm_model.state_dict() if base_model: remove_classification_head_(_lowerCAmelCase ) lowerCamelCase_ : int = create_rename_keys(_lowerCAmelCase , _lowerCAmelCase ) for src, dest in rename_keys: rename_key(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) read_in_q_k_v(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) lowerCamelCase_ : List[str] = """huggingface/label-files""" lowerCamelCase_ : Any = """imagenet-1k-id2label.json""" lowerCamelCase_ : int = json.load(open(hf_hub_download(_lowerCAmelCase , _lowerCAmelCase , repo_type="""dataset""" ) , """r""" ) ) lowerCamelCase_ : List[Any] = {int(_lowerCAmelCase ): v for k, v in idalabel.items()} lowerCamelCase_ : Optional[int] = idalabel lowerCamelCase_ : Optional[Any] = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": lowerCamelCase_ : Any = ViTHybridModel(_lowerCAmelCase ).eval() else: lowerCamelCase_ : int = ViTHybridForImageClassification(_lowerCAmelCase ).eval() model.load_state_dict(_lowerCAmelCase ) # create image processor lowerCamelCase_ : List[Any] = create_transform(**resolve_data_config({} , model=_lowerCAmelCase ) ) lowerCamelCase_ : Tuple = transform.transforms lowerCamelCase_ : int = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } lowerCamelCase_ : Dict = ViTHybridImageProcessor( do_resize=_lowerCAmelCase , size={"""shortest_edge""": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_lowerCAmelCase , crop_size={"""height""": timm_transforms[1].size[0], """width""": timm_transforms[1].size[1]} , do_normalize=_lowerCAmelCase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) lowerCamelCase_ : str = prepare_img() lowerCamelCase_ : Union[str, Any] = transform(_lowerCAmelCase ).unsqueeze(0 ) lowerCamelCase_ : Union[str, Any] = processor(_lowerCAmelCase , return_tensors="""pt""" ).pixel_values # verify pixel values assert torch.allclose(_lowerCAmelCase , _lowerCAmelCase ) # verify logits with torch.no_grad(): lowerCamelCase_ : Dict = model(_lowerCAmelCase ) lowerCamelCase_ : Optional[int] = outputs.logits print("""Predicted class:""" , logits.argmax(-1 ).item() ) if base_model: lowerCamelCase_ : Optional[Any] = timm_model.forward_features(_lowerCAmelCase ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_lowerCAmelCase , outputs.pooler_output , atol=1e-3 ) else: lowerCamelCase_ : int = timm_model(_lowerCAmelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_lowerCAmelCase , outputs.logits , atol=1e-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) print(f'''Saving model {vit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_lowerCAmelCase ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(_lowerCAmelCase ) if push_to_hub: print(f'''Pushing model and processor to the hub {vit_name}''' ) model.push_to_hub(f'''ybelkada/{vit_name}''' ) processor.push_to_hub(f'''ybelkada/{vit_name}''' ) if __name__ == "__main__": snake_case__ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_r50_s16_384', type=str, help='Name of the hybrid ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to upload the model to the HuggingFace hub.' ) snake_case__ : List[Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
278
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCAmelCase ={ "configuration_groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase =[ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase =[ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGroupViTModel", "TFGroupViTPreTrainedModel", "TFGroupViTTextModel", "TFGroupViTVisionModel", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys __lowerCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
333
0
import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class a__ ( snake_case__ ): def __init__( self , _A , _A=1_3 , _A=7 , _A=True , _A=True , _A=True , _A=True , _A=9_9 , _A=3_2 , _A=5 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=5_1_2 , _A=1_6 , _A=2 , _A=0.02 , _A=False , _A=True , _A="None" , _A=3 , _A=4 , _A=None , ): """simple docstring""" __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = seq_length __lowerCAmelCase = is_training __lowerCAmelCase = use_input_mask __lowerCAmelCase = use_token_type_ids __lowerCAmelCase = use_labels __lowerCAmelCase = vocab_size __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = max_position_embeddings __lowerCAmelCase = type_vocab_size __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = num_labels __lowerCAmelCase = num_choices __lowerCAmelCase = relative_attention __lowerCAmelCase = position_biased_input __lowerCAmelCase = pos_att_type __lowerCAmelCase = scope def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase = None if self.use_input_mask: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __lowerCAmelCase = None if self.use_token_type_ids: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase = None __lowerCAmelCase = None __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DebertaVaModel(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A , attention_mask=_A , token_type_ids=_A )[0] __lowerCAmelCase = model(_A , token_type_ids=_A )[0] __lowerCAmelCase = model(_A )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DebertaVaForMaskedLM(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = self.num_labels __lowerCAmelCase = DebertaVaForSequenceClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(_A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = self.num_labels __lowerCAmelCase = DebertaVaForTokenClassification(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DebertaVaForQuestionAnswering(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DebertaVaForMultipleChoice(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCAmelCase = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = config_and_inputs __lowerCAmelCase = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class a__ ( snake_case__ , snake_case__ , unittest.TestCase ): _a : Dict = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) _a : List[Any] = ( { """feature-extraction""": DebertaVaModel, """fill-mask""": DebertaVaForMaskedLM, """question-answering""": DebertaVaForQuestionAnswering, """text-classification""": DebertaVaForSequenceClassification, """token-classification""": DebertaVaForTokenClassification, """zero-shot""": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) _a : Optional[int] = True _a : Union[str, Any] = False _a : Tuple = False _a : int = False _a : str = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DebertaVaModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=_A , hidden_size=3_7 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*_A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = DebertaVaModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @require_torch @require_sentencepiece @require_tokenizers class a__ ( unittest.TestCase ): @unittest.skip(reason="Model not available yet" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DebertaVaModel.from_pretrained("microsoft/deberta-v2-xlarge" ) __lowerCAmelCase = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) __lowerCAmelCase = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowerCAmelCase = model(_A , attention_mask=_A )[0] # compare the actual values for a slice. __lowerCAmelCase = torch.tensor( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _A , atol=1E-4 ) , f"""{output[:, 1:4, 1:4]}""" )
700
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCamelCase__ = { """configuration_ctrl""": ["""CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CTRLConfig"""], """tokenization_ctrl""": ["""CTRLTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """CTRL_PRETRAINED_MODEL_ARCHIVE_LIST""", """CTRLForSequenceClassification""", """CTRLLMHeadModel""", """CTRLModel""", """CTRLPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFCTRLForSequenceClassification""", """TFCTRLLMHeadModel""", """TFCTRLModel""", """TFCTRLPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
552
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ = { '''configuration_roberta''': ['''ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RobertaConfig''', '''RobertaOnnxConfig'''], '''tokenization_roberta''': ['''RobertaTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''RobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RobertaForCausalLM''', '''RobertaForMaskedLM''', '''RobertaForMultipleChoice''', '''RobertaForQuestionAnswering''', '''RobertaForSequenceClassification''', '''RobertaForTokenClassification''', '''RobertaModel''', '''RobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRobertaForCausalLM''', '''TFRobertaForMaskedLM''', '''TFRobertaForMultipleChoice''', '''TFRobertaForQuestionAnswering''', '''TFRobertaForSequenceClassification''', '''TFRobertaForTokenClassification''', '''TFRobertaMainLayer''', '''TFRobertaModel''', '''TFRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''FlaxRobertaForCausalLM''', '''FlaxRobertaForMaskedLM''', '''FlaxRobertaForMultipleChoice''', '''FlaxRobertaForQuestionAnswering''', '''FlaxRobertaForSequenceClassification''', '''FlaxRobertaForTokenClassification''', '''FlaxRobertaModel''', '''FlaxRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
95
"""simple docstring""" from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging lowerCamelCase_ = logging.get_logger(__name__) class UpperCamelCase_ : __magic_name__ = 42 __magic_name__ = None @staticmethod def _SCREAMING_SNAKE_CASE ( ) -> Optional[int]: raise NotImplementedError def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : str , **lowerCAmelCase_ : Union[str, Any] ) -> Optional[Any]: raise NotImplementedError def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : Union[str, Any] ) -> str: raise NotImplementedError def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: if not self.is_available(): raise RuntimeError( f"""You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.""" ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple ) -> List[str]: return f"""`pip install {cls.pip_package or cls.name}`""" class UpperCamelCase_ (__A ): __magic_name__ = '''optuna''' @staticmethod def _SCREAMING_SNAKE_CASE ( ) -> List[str]: return is_optuna_available() def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : str , **lowerCAmelCase_ : Tuple ) -> int: return run_hp_search_optuna(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowerCAmelCase_ : Dict ) -> Optional[Any]: return default_hp_space_optuna(lowerCAmelCase_ ) class UpperCamelCase_ (__A ): __magic_name__ = '''ray''' __magic_name__ = '''\'ray[tune]\'''' @staticmethod def _SCREAMING_SNAKE_CASE ( ) -> Optional[int]: return is_ray_available() def _SCREAMING_SNAKE_CASE ( self : List[str] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : str , **lowerCAmelCase_ : Tuple ) -> List[str]: return run_hp_search_ray(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase_ : Tuple ) -> Optional[int]: return default_hp_space_ray(lowerCAmelCase_ ) class UpperCamelCase_ (__A ): __magic_name__ = '''sigopt''' @staticmethod def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: return is_sigopt_available() def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase_ : str , lowerCAmelCase_ : int , lowerCAmelCase_ : str , **lowerCAmelCase_ : str ) -> str: return run_hp_search_sigopt(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase_ : Any ) -> Any: return default_hp_space_sigopt(lowerCAmelCase_ ) class UpperCamelCase_ (__A ): __magic_name__ = '''wandb''' @staticmethod def _SCREAMING_SNAKE_CASE ( ) -> int: return is_wandb_available() def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : int , lowerCAmelCase_ : str , **lowerCAmelCase_ : Optional[Any] ) -> Optional[Any]: return run_hp_search_wandb(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : List[str] ) -> Any: return default_hp_space_wandb(lowerCAmelCase_ ) lowerCamelCase_ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def snake_case ( ): UpperCAmelCase_ : List[str] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(A__ ) > 0: UpperCAmelCase_ : Optional[Any] = available_backends[0].name if len(A__ ) > 1: logger.info( F"""{len(A__ )} hyperparameter search backends available. Using {name} as the default.""" ) return name raise RuntimeError( "No hyperparameter search backend available.\n" + "\n".join( F""" - To install {backend.name} run {backend.pip_install()}""" for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
95
1
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class lowercase__( snake_case__ ): '''simple docstring''' snake_case__ = 4_2 snake_case__ = jnp.floataa snake_case__ = True def UpperCAmelCase ( self) -> str: """simple docstring""" super().setup() UpperCamelCase__ : str =nn.Dense(5 , dtype=self.dtype) def __call__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) -> str: """simple docstring""" UpperCamelCase__ : Optional[int] =super().__call__(*__A , **__A) UpperCamelCase__ : int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class lowercase__( snake_case__ ): '''simple docstring''' snake_case__ = FlaxBigBirdForNaturalQuestionsModule def _lowerCamelCase ( A_ : Optional[Any] , A_ : Dict , A_ : int , A_ : Optional[int] , A_ : Tuple , A_ : Dict ) -> Optional[Any]: '''simple docstring''' def cross_entropy(A_ : Dict , A_ : str , A_ : Tuple=None ): UpperCamelCase__ : Optional[int] =logits.shape[-1] UpperCamelCase__ : Optional[Any] =(labels[..., None] == jnp.arange(_lowerCAmelCase )[None]).astype("f4" ) UpperCamelCase__ : str =jax.nn.log_softmax(_lowerCAmelCase , axis=-1 ) UpperCamelCase__ : int =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: UpperCamelCase__ : List[Any] =reduction(_lowerCAmelCase ) return loss UpperCamelCase__ : int =partial(_lowerCAmelCase , reduction=jnp.mean ) UpperCamelCase__ : List[Any] =cross_entropy(_lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase__ : Union[str, Any] =cross_entropy(_lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase__ : Optional[int] =cross_entropy(_lowerCAmelCase , _lowerCAmelCase ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class lowercase__: '''simple docstring''' snake_case__ = '''google/bigbird-roberta-base''' snake_case__ = 3_0_0_0 snake_case__ = 1_0_5_0_0 snake_case__ = 1_2_8 snake_case__ = 3 snake_case__ = 1 snake_case__ = 5 # tx_args snake_case__ = 3E-5 snake_case__ = 0.0 snake_case__ = 2_0_0_0_0 snake_case__ = 0.0095 snake_case__ = '''bigbird-roberta-natural-questions''' snake_case__ = '''training-expt''' snake_case__ = '''data/nq-training.jsonl''' snake_case__ = '''data/nq-validation.jsonl''' def UpperCAmelCase ( self) -> int: """simple docstring""" os.makedirs(self.base_dir , exist_ok=__A) UpperCamelCase__ : Union[str, Any] =os.path.join(self.base_dir , self.save_dir) UpperCamelCase__ : Any =self.batch_size_per_device * jax.device_count() @dataclass class lowercase__: '''simple docstring''' snake_case__ = 4_2 snake_case__ = 4_0_9_6 # no dynamic padding on TPUs def __call__( self , __SCREAMING_SNAKE_CASE) -> List[Any]: """simple docstring""" UpperCamelCase__ : Dict =self.collate_fn(__A) UpperCamelCase__ : int =jax.tree_util.tree_map(__A , __A) return batch def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE) -> str: """simple docstring""" UpperCamelCase__ : Union[str, Any] =self.fetch_inputs(features["input_ids"]) UpperCamelCase__ : Dict ={ "input_ids": jnp.array(__A , dtype=jnp.intaa), "attention_mask": jnp.array(__A , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE) -> int: """simple docstring""" UpperCamelCase__ : str =[self._fetch_inputs(__A) for ids in input_ids] return zip(*__A) def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE) -> Optional[Any]: """simple docstring""" UpperCamelCase__ : str =[1 for _ in range(len(__A))] while len(__A) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def _lowerCamelCase ( A_ : Any , A_ : List[str] , A_ : Dict=None ) -> Optional[int]: '''simple docstring''' if seed is not None: UpperCamelCase__ : Union[str, Any] =dataset.shuffle(seed=_lowerCAmelCase ) for i in range(len(_lowerCAmelCase ) // batch_size ): UpperCamelCase__ : Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(_lowerCAmelCase ) @partial(jax.pmap , axis_name="batch" ) def _lowerCamelCase ( A_ : Union[str, Any] , A_ : List[str] , **A_ : Optional[int] ) -> Optional[int]: '''simple docstring''' def loss_fn(A_ : str ): UpperCamelCase__ : List[Any] =model_inputs.pop("start_labels" ) UpperCamelCase__ : Union[str, Any] =model_inputs.pop("end_labels" ) UpperCamelCase__ : Optional[int] =model_inputs.pop("pooled_labels" ) UpperCamelCase__ : List[str] =state.apply_fn(**_lowerCAmelCase , params=_lowerCAmelCase , dropout_rng=_lowerCAmelCase , train=_lowerCAmelCase ) UpperCamelCase__ : Optional[Any] =outputs return state.loss_fn( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , ) UpperCamelCase__ : List[Any] =jax.random.split(_lowerCAmelCase ) UpperCamelCase__ : Tuple =jax.value_and_grad(_lowerCAmelCase ) UpperCamelCase__ : int =grad_fn(state.params ) UpperCamelCase__ : Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) UpperCamelCase__ : Union[str, Any] =jax.lax.pmean(_lowerCAmelCase , "batch" ) UpperCamelCase__ : Union[str, Any] =state.apply_gradients(grads=_lowerCAmelCase ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def _lowerCamelCase ( A_ : int , **A_ : Tuple ) -> Tuple: '''simple docstring''' UpperCamelCase__ : Optional[Any] =model_inputs.pop("start_labels" ) UpperCamelCase__ : Any =model_inputs.pop("end_labels" ) UpperCamelCase__ : Any =model_inputs.pop("pooled_labels" ) UpperCamelCase__ : Optional[int] =state.apply_fn(**_lowerCAmelCase , params=state.params , train=_lowerCAmelCase ) UpperCamelCase__ : Dict =outputs UpperCamelCase__ : List[str] =state.loss_fn(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase__ : Union[str, Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class lowercase__( train_state.TrainState ): '''simple docstring''' snake_case__ = struct.field(pytree_node=snake_case__ ) @dataclass class lowercase__: '''simple docstring''' snake_case__ = 4_2 snake_case__ = 4_2 snake_case__ = 4_2 snake_case__ = 4_2 snake_case__ = 4_2 snake_case__ = 4_2 snake_case__ = None def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None) -> Any: """simple docstring""" UpperCamelCase__ : Optional[Any] =model.params UpperCamelCase__ : List[Any] =TrainState.create( apply_fn=model.__call__ , params=__A , tx=__A , loss_fn=__A , ) if ckpt_dir is not None: UpperCamelCase__ : List[Any] =restore_checkpoint(__A , __A) UpperCamelCase__ : List[str] ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } UpperCamelCase__ : Any =build_tx(**__A) UpperCamelCase__ : int =train_state.TrainState( step=__A , apply_fn=model.__call__ , params=__A , tx=__A , opt_state=__A , ) UpperCamelCase__ : int =args UpperCamelCase__ : str =data_collator UpperCamelCase__ : Tuple =lr UpperCamelCase__ : Tuple =params UpperCamelCase__ : Tuple =jax_utils.replicate(__A) return state def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ : str =self.args UpperCamelCase__ : Union[str, Any] =len(__A) // args.batch_size UpperCamelCase__ : Dict =jax.random.PRNGKey(0) UpperCamelCase__ : Optional[int] =jax.random.split(__A , jax.device_count()) for epoch in range(args.max_epochs): UpperCamelCase__ : List[str] =jnp.array(0 , dtype=jnp.floataa) UpperCamelCase__ : Any =get_batched_dataset(__A , args.batch_size , seed=__A) UpperCamelCase__ : Union[str, Any] =0 for batch in tqdm(__A , total=__A , desc=F'''Running EPOCH-{epoch}'''): UpperCamelCase__ : Optional[Any] =self.data_collator(__A) UpperCamelCase__ : Optional[Any] =self.train_step_fn(__A , __A , **__A) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: UpperCamelCase__ : Dict =jax_utils.unreplicate(state.step) UpperCamelCase__ : Optional[Any] =running_loss.item() / i UpperCamelCase__ : Tuple =self.scheduler_fn(state_step - 1) UpperCamelCase__ : Any =self.evaluate(__A , __A) UpperCamelCase__ : str ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(__A)) self.logger.log(__A , commit=__A) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F'''-e{epoch}-s{i}''' , state=__A) def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) -> List[str]: """simple docstring""" UpperCamelCase__ : List[Any] =get_batched_dataset(__A , self.args.batch_size) UpperCamelCase__ : str =len(__A) // self.args.batch_size UpperCamelCase__ : Optional[Any] =jnp.array(0 , dtype=jnp.floataa) UpperCamelCase__ : Dict =0 for batch in tqdm(__A , total=__A , desc="Evaluating ... "): UpperCamelCase__ : str =self.data_collator(__A) UpperCamelCase__ : Dict =self.val_step_fn(__A , **__A) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) -> List[Any]: """simple docstring""" UpperCamelCase__ : Any =jax_utils.unreplicate(__A) print(F'''SAVING CHECKPOINT IN {save_dir}''' , end=" ... ") self.model_save_fn(__A , params=state.params) with open(os.path.join(__A , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(__A , "args.joblib")) joblib.dump(self.data_collator , os.path.join(__A , "data_collator.joblib")) with open(os.path.join(__A , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , __A) print("DONE") def _lowerCamelCase ( A_ : Optional[Any] , A_ : List[str] ) -> Optional[int]: '''simple docstring''' print(f'''RESTORING CHECKPOINT FROM {save_dir}''' , end=" ... " ) with open(os.path.join(_lowerCAmelCase , "flax_model.msgpack" ) , "rb" ) as f: UpperCamelCase__ : str =from_bytes(state.params , f.read() ) with open(os.path.join(_lowerCAmelCase , "opt_state.msgpack" ) , "rb" ) as f: UpperCamelCase__ : List[Any] =from_bytes(state.opt_state , f.read() ) UpperCamelCase__ : Optional[int] =joblib.load(os.path.join(_lowerCAmelCase , "args.joblib" ) ) UpperCamelCase__ : List[Any] =joblib.load(os.path.join(_lowerCAmelCase , "data_collator.joblib" ) ) with open(os.path.join(_lowerCAmelCase , "training_state.json" ) , "r" ) as f: UpperCamelCase__ : str =json.load(_lowerCAmelCase ) UpperCamelCase__ : Union[str, Any] =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def _lowerCamelCase ( A_ : Optional[int] , A_ : int , A_ : List[str] , A_ : str ) -> Any: '''simple docstring''' UpperCamelCase__ : List[str] =num_train_steps - warmup_steps UpperCamelCase__ : Dict =optax.linear_schedule(init_value=_lowerCAmelCase , end_value=_lowerCAmelCase , transition_steps=_lowerCAmelCase ) UpperCamelCase__ : Dict =optax.linear_schedule(init_value=_lowerCAmelCase , end_value=1E-7 , transition_steps=_lowerCAmelCase ) UpperCamelCase__ : List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def _lowerCamelCase ( A_ : Dict , A_ : int , A_ : Optional[int] , A_ : Dict , A_ : Optional[int] ) -> str: '''simple docstring''' def weight_decay_mask(A_ : List[Any] ): UpperCamelCase__ : Tuple =traverse_util.flatten_dict(_lowerCAmelCase ) UpperCamelCase__ : Tuple ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(_lowerCAmelCase ) UpperCamelCase__ : int =scheduler_fn(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase__ : Optional[Any] =optax.adamw(learning_rate=_lowerCAmelCase , weight_decay=_lowerCAmelCase , mask=_lowerCAmelCase ) return tx, lr
711
import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser( description=( """Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned""" """ Distillation""" ) ) parser.add_argument("""--model_type""", default="""roberta""", choices=["""roberta""", """gpt2"""]) parser.add_argument("""--model_name""", default="""roberta-large""", type=str) parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_roberta_048131723.pth""", type=str) parser.add_argument("""--vocab_transform""", action="""store_true""") __UpperCAmelCase = parser.parse_args() if args.model_type == "roberta": __UpperCAmelCase = RobertaForMaskedLM.from_pretrained(args.model_name) __UpperCAmelCase = """roberta""" elif args.model_type == "gpt2": __UpperCAmelCase = GPTaLMHeadModel.from_pretrained(args.model_name) __UpperCAmelCase = """transformer""" __UpperCAmelCase = model.state_dict() __UpperCAmelCase = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: __UpperCAmelCase = state_dict[F"""{prefix}.{param_name}"""] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: __UpperCAmelCase = F"""{prefix}.embeddings.{w}.weight""" __UpperCAmelCase = state_dict[param_name] for w in ["weight", "bias"]: __UpperCAmelCase = F"""{prefix}.embeddings.LayerNorm.{w}""" __UpperCAmelCase = state_dict[param_name] # Transformer Blocks # __UpperCAmelCase = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: __UpperCAmelCase = state_dict[ F"""{prefix}.h.{teacher_idx}.{layer}.{w}""" ] __UpperCAmelCase = state_dict[F"""{prefix}.h.{teacher_idx}.attn.bias"""] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: __UpperCAmelCase = state_dict[ F"""{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}""" ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: __UpperCAmelCase = state_dict[F"""{layer}"""] if args.vocab_transform: for w in ["weight", "bias"]: __UpperCAmelCase = state_dict[F"""lm_head.dense.{w}"""] __UpperCAmelCase = state_dict[F"""lm_head.layer_norm.{w}"""] elif args.model_type == "gpt2": for w in ["weight", "bias"]: __UpperCAmelCase = state_dict[F"""{prefix}.ln_f.{w}"""] __UpperCAmelCase = state_dict["""lm_head.weight"""] print(F"""N layers selected for distillation: {std_idx}""") print(F"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(F"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
582
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A : List[Any] = logging.get_logger(__name__) __A : Dict = { '''uclanlp/visualbert-vqa''': '''https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json''', '''uclanlp/visualbert-vqa-pre''': '''https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json''', '''uclanlp/visualbert-vqa-coco-pre''': ( '''https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json''' ), '''uclanlp/visualbert-vcr''': '''https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json''', '''uclanlp/visualbert-vcr-pre''': '''https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json''', '''uclanlp/visualbert-vcr-coco-pre''': ( '''https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json''' ), '''uclanlp/visualbert-nlvr2''': '''https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json''', '''uclanlp/visualbert-nlvr2-pre''': '''https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json''', '''uclanlp/visualbert-nlvr2-coco-pre''': ( '''https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json''' ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class __A ( _SCREAMING_SNAKE_CASE ): lowerCAmelCase_ : Union[str, Any] = 'visual_bert' def __init__( self : Union[str, Any] , UpperCAmelCase_ : Tuple=30522 , UpperCAmelCase_ : List[str]=768 , UpperCAmelCase_ : str=512 , UpperCAmelCase_ : Tuple=12 , UpperCAmelCase_ : Tuple=12 , UpperCAmelCase_ : Tuple=3072 , UpperCAmelCase_ : List[str]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : List[Any]=512 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Union[str, Any]=1E-12 , UpperCAmelCase_ : str=False , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Union[str, Any]=1 , UpperCAmelCase_ : str=0 , UpperCAmelCase_ : Optional[int]=2 , **UpperCAmelCase_ : Dict , ): super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ ) lowerCAmelCase : List[Any] = vocab_size lowerCAmelCase : Optional[int] = max_position_embeddings lowerCAmelCase : Union[str, Any] = hidden_size lowerCAmelCase : Optional[int] = visual_embedding_dim lowerCAmelCase : List[Any] = num_hidden_layers lowerCAmelCase : Union[str, Any] = num_attention_heads lowerCAmelCase : int = intermediate_size lowerCAmelCase : Any = hidden_act lowerCAmelCase : Optional[Any] = hidden_dropout_prob lowerCAmelCase : int = attention_probs_dropout_prob lowerCAmelCase : Union[str, Any] = initializer_range lowerCAmelCase : str = type_vocab_size lowerCAmelCase : Optional[int] = layer_norm_eps lowerCAmelCase : str = bypass_transformer lowerCAmelCase : List[Any] = special_visual_initialize
343
"""simple docstring""" # Algorithm for the pigeonhole sorting def __a ( a ): """simple docstring""" _a = min(a ) # min() finds the minimum value _a = max(a ) # max() finds the maximum value _a = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size _a = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(a, a ), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. _a = 0 for count in range(a ): while holes[count] > 0: holes[count] -= 1 _a = count + min_val i += 1 def __a ( ): """simple docstring""" _a = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(a ) print("Sorted order is:", " ".join(a ) ) if __name__ == "__main__": main()
388
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { '''kssteven/ibert-roberta-base''': '''https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json''', '''kssteven/ibert-roberta-large''': '''https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json''', '''kssteven/ibert-roberta-large-mnli''': ( '''https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json''' ), } class lowercase ( A__ ): """simple docstring""" _a = 'ibert' def __init__( self , UpperCamelCase_=30522 , UpperCamelCase_=768 , UpperCamelCase_=12 , UpperCamelCase_=12 , UpperCamelCase_=3072 , UpperCamelCase_="gelu" , UpperCamelCase_=0.1 , UpperCamelCase_=0.1 , UpperCamelCase_=512 , UpperCamelCase_=2 , UpperCamelCase_=0.02 , UpperCamelCase_=1e-12 , UpperCamelCase_=1 , UpperCamelCase_=0 , UpperCamelCase_=2 , UpperCamelCase_="absolute" , UpperCamelCase_=False , UpperCamelCase_="none" , **UpperCamelCase_ , ): '''simple docstring''' super().__init__(pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_ ) UpperCamelCase__ :Tuple = vocab_size UpperCamelCase__ :Union[str, Any] = hidden_size UpperCamelCase__ :List[str] = num_hidden_layers UpperCamelCase__ :List[Any] = num_attention_heads UpperCamelCase__ :Optional[int] = hidden_act UpperCamelCase__ :str = intermediate_size UpperCamelCase__ :Dict = hidden_dropout_prob UpperCamelCase__ :Optional[int] = attention_probs_dropout_prob UpperCamelCase__ :Tuple = max_position_embeddings UpperCamelCase__ :List[Any] = type_vocab_size UpperCamelCase__ :str = initializer_range UpperCamelCase__ :Any = layer_norm_eps UpperCamelCase__ :str = position_embedding_type UpperCamelCase__ :Union[str, Any] = quant_mode UpperCamelCase__ :Optional[int] = force_dequant class lowercase ( A__ ): """simple docstring""" @property def lowerCAmelCase__ ( self ): '''simple docstring''' if self.task == "multiple-choice": UpperCamelCase__ :Optional[int] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: UpperCamelCase__ :Dict = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
716
'''simple docstring''' import json import logging import os import sys from time import time from unittest.mock import patch from transformers.testing_utils import TestCasePlus, require_torch_tpu logging.basicConfig(level=logging.DEBUG) __snake_case = logging.getLogger() def a ( __a ) -> Dict: '''simple docstring''' UpperCamelCase__ :str = {} UpperCamelCase__ :Dict = os.path.join(__a , '''all_results.json''' ) if os.path.exists(__a ): with open(__a , '''r''' ) as f: UpperCamelCase__ :int = json.load(__a ) else: raise ValueError(f'''can\'t find {path}''' ) return results __snake_case = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @require_torch_tpu class lowercase ( A__ ): """simple docstring""" def lowerCAmelCase__ ( self ): '''simple docstring''' import xla_spawn UpperCamelCase__ :Any = self.get_auto_remove_tmp_dir() UpperCamelCase__ :List[str] = F''' ./examples/pytorch/text-classification/run_glue.py --num_cores=8 ./examples/pytorch/text-classification/run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --overwrite_output_dir --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --do_train --do_eval --debug tpu_metrics_debug --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --max_steps=10 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(UpperCamelCase_ , '''argv''' , UpperCamelCase_ ): UpperCamelCase__ :List[Any] = time() xla_spawn.main() UpperCamelCase__ :List[Any] = time() UpperCamelCase__ :Tuple = get_results(UpperCamelCase_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) # Assert that the script takes less than 500 seconds to make sure it doesn't hang. self.assertLess(end - start , 500 ) def lowerCAmelCase__ ( self ): '''simple docstring''' import xla_spawn UpperCamelCase__ :Tuple = ''' ./tests/test_trainer_tpu.py --num_cores=8 ./tests/test_trainer_tpu.py '''.split() with patch.object(UpperCamelCase_ , '''argv''' , UpperCamelCase_ ): xla_spawn.main()
280
0
"""simple docstring""" import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _a ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase): __magic_name__ = StableDiffusionDiffEditPipeline __magic_name__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""height""", """width""", """image"""} | {"""image_latents"""} __magic_name__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"""image"""} | {"""image_latents"""} __magic_name__ = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __magic_name__ = frozenset([]) def __lowercase ( self : List[str] ) -> Any: torch.manual_seed(0 ) snake_case : Dict = 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 , attention_head_dim=(2, 4) , use_linear_projection=_lowercase , ) snake_case : Dict = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=_lowercase , set_alpha_to_one=_lowercase , ) snake_case : Any = DDIMInverseScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=_lowercase , set_alpha_to_zero=_lowercase , ) torch.manual_seed(0 ) snake_case : int = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="gelu" , projection_dim=512 , ) snake_case : Union[str, Any] = CLIPTextModel(_lowercase ) snake_case : Tuple = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) snake_case : Tuple = { "unet": unet, "scheduler": scheduler, "inverse_scheduler": inverse_scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def __lowercase ( self : List[str] , _lowercase : Union[str, Any] , _lowercase : Optional[Any]=0 ) -> str: snake_case : List[Any] = floats_tensor((1, 16, 16) , rng=random.Random(_lowercase ) ).to(_lowercase ) snake_case : Any = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(_lowercase ) ).to(_lowercase ) if str(_lowercase ).startswith("mps" ): snake_case : int = torch.manual_seed(_lowercase ) else: snake_case : Optional[int] = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) snake_case : Any = { "prompt": "a dog and a newt", "mask_image": mask, "image_latents": latents, "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def __lowercase ( self : Optional[int] , _lowercase : List[str] , _lowercase : str=0 ) -> Any: snake_case : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowercase ) ).to(_lowercase ) snake_case : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] snake_case : Union[str, Any] = Image.fromarray(np.uinta(_lowercase ) ).convert("RGB" ) if str(_lowercase ).startswith("mps" ): snake_case : Tuple = torch.manual_seed(_lowercase ) else: snake_case : List[Any] = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) snake_case : Union[str, Any] = { "image": image, "source_prompt": "a cat and a frog", "target_prompt": "a dog and a newt", "generator": generator, "num_inference_steps": 2, "num_maps_per_mask": 2, "mask_encode_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def __lowercase ( self : Any , _lowercase : int , _lowercase : Union[str, Any]=0 ) -> List[str]: snake_case : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowercase ) ).to(_lowercase ) snake_case : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] snake_case : Tuple = Image.fromarray(np.uinta(_lowercase ) ).convert("RGB" ) if str(_lowercase ).startswith("mps" ): snake_case : List[Any] = torch.manual_seed(_lowercase ) else: snake_case : List[Any] = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) snake_case : str = { "image": image, "prompt": "a cat and a frog", "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "decode_latents": True, "output_type": "numpy", } return inputs def __lowercase ( self : Optional[Any] ) -> Tuple: if not hasattr(self.pipeline_class , "_optional_components" ): return snake_case : Tuple = self.get_dummy_components() snake_case : str = self.pipeline_class(**_lowercase ) pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(_lowercase , _lowercase , _lowercase ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) snake_case : Optional[Any] = self.get_dummy_inputs(_lowercase ) snake_case : Dict = pipe(**_lowercase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_lowercase ) snake_case : Tuple = self.pipeline_class.from_pretrained(_lowercase ) pipe_loaded.to(_lowercase ) pipe_loaded.set_progress_bar_config(disable=_lowercase ) for optional_component in pipe._optional_components: self.assertTrue( getattr(_lowercase , _lowercase ) is None , F'''`{optional_component}` did not stay set to None after loading.''' , ) snake_case : Tuple = self.get_dummy_inputs(_lowercase ) snake_case : str = pipe_loaded(**_lowercase )[0] snake_case : List[Any] = np.abs(output - output_loaded ).max() self.assertLess(_lowercase , 1E-4 ) def __lowercase ( self : Union[str, Any] ) -> List[str]: snake_case : Tuple = "cpu" snake_case : Optional[int] = self.get_dummy_components() snake_case : List[str] = self.pipeline_class(**_lowercase ) pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) snake_case : Tuple = self.get_dummy_mask_inputs(_lowercase ) snake_case : str = pipe.generate_mask(**_lowercase ) snake_case : Optional[Any] = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) snake_case : str = np.array([0] * 9 ) snake_case : Tuple = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowercase , 1E-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def __lowercase ( self : str ) -> int: snake_case : str = "cpu" snake_case : Optional[Any] = self.get_dummy_components() snake_case : Dict = self.pipeline_class(**_lowercase ) pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) snake_case : int = self.get_dummy_inversion_inputs(_lowercase ) snake_case : Union[str, Any] = pipe.invert(**_lowercase ).images snake_case : Dict = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) snake_case : Optional[int] = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) snake_case : List[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowercase , 1E-3 ) def __lowercase ( self : Optional[Any] ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=5E-3 ) def __lowercase ( self : List[Any] ) -> Optional[int]: snake_case : str = "cpu" snake_case : Optional[Any] = self.get_dummy_components() snake_case : Union[str, Any] = {"beta_start": 0.00085, "beta_end": 0.012, "beta_schedule": "scaled_linear"} snake_case : Tuple = DPMSolverMultistepScheduler(**_lowercase ) snake_case : int = DPMSolverMultistepInverseScheduler(**_lowercase ) snake_case : Union[str, Any] = self.pipeline_class(**_lowercase ) pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) snake_case : str = self.get_dummy_inversion_inputs(_lowercase ) snake_case : Optional[Any] = pipe.invert(**_lowercase ).images snake_case : Optional[Any] = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) snake_case : List[str] = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) snake_case : Optional[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowercase , 1E-3 ) @require_torch_gpu @slow class _a ( unittest.TestCase): def __lowercase ( self : str ) -> Optional[int]: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def __lowercase ( cls : Optional[int] ) -> Optional[Any]: snake_case : Any = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png" ) snake_case : str = raw_image.convert("RGB" ).resize((768, 768) ) snake_case : Tuple = raw_image def __lowercase ( self : Tuple ) -> int: snake_case : int = torch.manual_seed(0 ) snake_case : List[Any] = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=_lowercase , torch_dtype=torch.floataa ) snake_case : List[str] = DDIMScheduler.from_config(pipe.scheduler.config ) snake_case : int = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=_lowercase ) snake_case : int = "a bowl of fruit" snake_case : Any = "a bowl of pears" snake_case : Tuple = pipe.generate_mask( image=self.raw_image , source_prompt=_lowercase , target_prompt=_lowercase , generator=_lowercase , ) snake_case : Any = pipe.invert( prompt=_lowercase , image=self.raw_image , inpaint_strength=0.7 , generator=_lowercase ).latents snake_case : Any = pipe( prompt=_lowercase , mask_image=_lowercase , image_latents=_lowercase , generator=_lowercase , negative_prompt=_lowercase , inpaint_strength=0.7 , output_type="numpy" , ).images[0] snake_case : List[str] = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1 def __lowercase ( self : str ) -> int: snake_case : Any = torch.manual_seed(0 ) snake_case : List[str] = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" , safety_checker=_lowercase , torch_dtype=torch.floataa ) snake_case : Tuple = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) snake_case : str = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=_lowercase ) snake_case : List[str] = "a bowl of fruit" snake_case : List[Any] = "a bowl of pears" snake_case : int = pipe.generate_mask( image=self.raw_image , source_prompt=_lowercase , target_prompt=_lowercase , generator=_lowercase , ) snake_case : List[str] = pipe.invert( prompt=_lowercase , image=self.raw_image , inpaint_strength=0.7 , generator=_lowercase , num_inference_steps=25 , ).latents snake_case : str = pipe( prompt=_lowercase , mask_image=_lowercase , image_latents=_lowercase , generator=_lowercase , negative_prompt=_lowercase , inpaint_strength=0.7 , num_inference_steps=25 , output_type="numpy" , ).images[0] snake_case : Tuple = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1
449
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class _a ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase): __magic_name__ = StableDiffusionPanoramaPipeline __magic_name__ = TEXT_TO_IMAGE_PARAMS __magic_name__ = TEXT_TO_IMAGE_BATCH_PARAMS __magic_name__ = TEXT_TO_IMAGE_IMAGE_PARAMS __magic_name__ = TEXT_TO_IMAGE_IMAGE_PARAMS def __lowercase ( self : Optional[int] ) -> int: torch.manual_seed(0 ) snake_case : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) snake_case : Tuple = DDIMScheduler() torch.manual_seed(0 ) snake_case : List[Any] = 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 ) snake_case : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) snake_case : int = CLIPTextModel(_lowercase ) snake_case : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) snake_case : Any = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def __lowercase ( self : List[str] , _lowercase : int , _lowercase : Dict=0 ) -> Optional[int]: snake_case : Union[str, Any] = torch.manual_seed(_lowercase ) snake_case : str = { "prompt": "a photo of the dolomites", "generator": generator, # Setting height and width to None to prevent OOMs on CPU. "height": None, "width": None, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def __lowercase ( self : str ) -> List[str]: snake_case : Any = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case : Dict = self.get_dummy_components() snake_case : Any = StableDiffusionPanoramaPipeline(**_lowercase ) snake_case : List[Any] = sd_pipe.to(_lowercase ) sd_pipe.set_progress_bar_config(disable=_lowercase ) snake_case : Optional[Any] = self.get_dummy_inputs(_lowercase ) snake_case : Union[str, Any] = sd_pipe(**_lowercase ).images snake_case : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case : List[Any] = np.array([0.6186, 0.5374, 0.4915, 0.4135, 0.4114, 0.4563, 0.5128, 0.4977, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowercase ( self : int ) -> Union[str, Any]: super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowercase ( self : Tuple ) -> Tuple: super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 ) def __lowercase ( self : Any ) -> List[Any]: snake_case : Any = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case : Union[str, Any] = self.get_dummy_components() snake_case : Tuple = StableDiffusionPanoramaPipeline(**_lowercase ) snake_case : Tuple = sd_pipe.to(_lowercase ) sd_pipe.set_progress_bar_config(disable=_lowercase ) snake_case : List[str] = self.get_dummy_inputs(_lowercase ) snake_case : int = "french fries" snake_case : Union[str, Any] = sd_pipe(**_lowercase , negative_prompt=_lowercase ) snake_case : str = output.images snake_case : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case : Union[str, Any] = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowercase ( self : str ) -> Any: snake_case : Optional[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case : List[Any] = self.get_dummy_components() snake_case : List[Any] = StableDiffusionPanoramaPipeline(**_lowercase ) snake_case : int = sd_pipe.to(_lowercase ) sd_pipe.set_progress_bar_config(disable=_lowercase ) snake_case : Tuple = self.get_dummy_inputs(_lowercase ) snake_case : str = sd_pipe(**_lowercase , view_batch_size=2 ) snake_case : Optional[Any] = output.images snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case : str = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowercase ( self : int ) -> Optional[Any]: snake_case : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case : List[str] = self.get_dummy_components() snake_case : Any = EulerAncestralDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" ) snake_case : List[str] = StableDiffusionPanoramaPipeline(**_lowercase ) snake_case : List[str] = sd_pipe.to(_lowercase ) sd_pipe.set_progress_bar_config(disable=_lowercase ) snake_case : List[Any] = self.get_dummy_inputs(_lowercase ) snake_case : Optional[Any] = sd_pipe(**_lowercase ).images snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case : Tuple = np.array([0.4024, 0.6510, 0.4901, 0.5378, 0.5813, 0.5622, 0.4795, 0.4467, 0.4952] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowercase ( self : Tuple ) -> Union[str, Any]: snake_case : str = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case : str = self.get_dummy_components() snake_case : Optional[int] = PNDMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , skip_prk_steps=_lowercase ) snake_case : Dict = StableDiffusionPanoramaPipeline(**_lowercase ) snake_case : Dict = sd_pipe.to(_lowercase ) sd_pipe.set_progress_bar_config(disable=_lowercase ) snake_case : Dict = self.get_dummy_inputs(_lowercase ) snake_case : Optional[int] = sd_pipe(**_lowercase ).images snake_case : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case : Optional[int] = np.array([0.6391, 0.6291, 0.4861, 0.5134, 0.5552, 0.4578, 0.5032, 0.5023, 0.4539] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class _a ( unittest.TestCase): def __lowercase ( self : Union[str, Any] ) -> str: super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self : Dict , _lowercase : Any=0 ) -> Optional[Any]: snake_case : Any = torch.manual_seed(_lowercase ) snake_case : Any = { "prompt": "a photo of the dolomites", "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def __lowercase ( self : Optional[Any] ) -> Union[str, Any]: snake_case : List[Any] = "stabilityai/stable-diffusion-2-base" snake_case : Dict = DDIMScheduler.from_pretrained(_lowercase , subfolder="scheduler" ) snake_case : Any = StableDiffusionPanoramaPipeline.from_pretrained(_lowercase , scheduler=_lowercase , safety_checker=_lowercase ) pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) pipe.enable_attention_slicing() snake_case : str = self.get_inputs() snake_case : List[Any] = pipe(**_lowercase ).images snake_case : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) snake_case : List[str] = np.array( [ 0.36968392, 0.27025372, 0.32446766, 0.28379387, 0.36363274, 0.30733347, 0.27100027, 0.27054125, 0.25536096, ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-2 def __lowercase ( self : Tuple ) -> List[str]: snake_case : List[str] = StableDiffusionPanoramaPipeline.from_pretrained( "stabilityai/stable-diffusion-2-base" , safety_checker=_lowercase ) snake_case : int = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) pipe.enable_attention_slicing() snake_case : Dict = self.get_inputs() snake_case : int = pipe(**_lowercase ).images snake_case : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) snake_case : List[str] = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def __lowercase ( self : str ) -> Any: snake_case : Any = 0 def callback_fn(_lowercase : int , _lowercase : int , _lowercase : torch.FloatTensor ) -> None: snake_case : List[Any] = True nonlocal number_of_steps number_of_steps += 1 if step == 1: snake_case : List[Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) snake_case : int = latents[0, -3:, -3:, -1] snake_case : Tuple = np.array( [ 0.18681869, 0.33907816, 0.5361276, 0.14432865, -0.02856611, -0.73941123, 0.23397987, 0.47322682, -0.37823164, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: snake_case : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) snake_case : Tuple = latents[0, -3:, -3:, -1] snake_case : Tuple = np.array( [ 0.18539645, 0.33987248, 0.5378559, 0.14437142, -0.02455261, -0.7338317, 0.23990755, 0.47356272, -0.3786505, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 snake_case : Dict = False snake_case : List[Any] = "stabilityai/stable-diffusion-2-base" snake_case : List[str] = DDIMScheduler.from_pretrained(_lowercase , subfolder="scheduler" ) snake_case : Optional[Any] = StableDiffusionPanoramaPipeline.from_pretrained(_lowercase , scheduler=_lowercase , safety_checker=_lowercase ) snake_case : Any = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) pipe.enable_attention_slicing() snake_case : Tuple = self.get_inputs() pipe(**_lowercase , callback=_lowercase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase ( self : Any ) -> Tuple: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() snake_case : Optional[int] = "stabilityai/stable-diffusion-2-base" snake_case : Tuple = DDIMScheduler.from_pretrained(_lowercase , subfolder="scheduler" ) snake_case : Any = StableDiffusionPanoramaPipeline.from_pretrained(_lowercase , scheduler=_lowercase , safety_checker=_lowercase ) snake_case : Tuple = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() snake_case : Any = self.get_inputs() snake_case : Optional[int] = pipe(**_lowercase ) snake_case : int = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
449
1
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging __lowercase = logging.get_logger(__name__) def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :int = set() __UpperCamelCase :int = [] def parse_line(SCREAMING_SNAKE_CASE ): for line in fp: if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): __UpperCamelCase :List[Any] = line.decode('''UTF-8''' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(''' ''' ): # process a single warning and move it to `selected_warnings`. if len(SCREAMING_SNAKE_CASE ) > 0: __UpperCamelCase :List[Any] = '''\n'''.join(SCREAMING_SNAKE_CASE ) # Only keep the warnings specified in `targets` if any(f""": {x}: """ in warning for x in targets ): selected_warnings.add(SCREAMING_SNAKE_CASE ) buffer.clear() continue else: __UpperCamelCase :str = line.strip() buffer.append(SCREAMING_SNAKE_CASE ) if from_gh: for filename in os.listdir(SCREAMING_SNAKE_CASE ): __UpperCamelCase :Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if not os.path.isdir(SCREAMING_SNAKE_CASE ): # read the file if filename != "warnings.txt": continue with open(SCREAMING_SNAKE_CASE ) as fp: parse_line(SCREAMING_SNAKE_CASE ) else: try: with zipfile.ZipFile(SCREAMING_SNAKE_CASE ) as z: for filename in z.namelist(): if not os.path.isdir(SCREAMING_SNAKE_CASE ): # read the file if filename != "warnings.txt": continue with z.open(SCREAMING_SNAKE_CASE ) as fp: parse_line(SCREAMING_SNAKE_CASE ) except Exception: logger.warning( f"""{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.""" ) return selected_warnings def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :Optional[Any] = set() __UpperCamelCase :Union[str, Any] = [os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for p in os.listdir(SCREAMING_SNAKE_CASE ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) return selected_warnings if __name__ == "__main__": def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' return values.split(''',''' ) __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.''') # optional parameters parser.add_argument( '''--targets''', default='''DeprecationWarning,UserWarning,FutureWarning''', type=list_str, help='''Comma-separated list of target warning(s) which we want to extract.''', ) parser.add_argument( '''--from_gh''', action='''store_true''', help='''If running from a GitHub action workflow and collecting warnings from its artifacts.''', ) __lowercase = parser.parse_args() __lowercase = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links __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) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print('''=''' * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts __lowercase = extract_warnings(args.output_dir, args.targets) __lowercase = sorted(selected_warnings) with open(os.path.join(args.output_dir, '''selected_warnings.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
452
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' a__ : Union[str, Any] = None a__ : Tuple = None @property def UpperCamelCase__ ( self) -> Any: return self.feat_extract_tester.prepare_feat_extract_dict() def UpperCamelCase__ ( self) -> List[str]: __UpperCamelCase :str = self.feature_extraction_class(**self.feat_extract_dict) self.assertTrue(hasattr(__lowercase , '''feature_size''')) self.assertTrue(hasattr(__lowercase , '''sampling_rate''')) self.assertTrue(hasattr(__lowercase , '''padding_value''')) def UpperCamelCase__ ( self) -> Tuple: __UpperCamelCase :str = self.feat_extract_tester.prepare_inputs_for_common() __UpperCamelCase :Optional[int] = self.feature_extraction_class(**self.feat_extract_dict) __UpperCamelCase :Optional[Any] = feat_extract.model_input_names[0] __UpperCamelCase :Union[str, Any] = BatchFeature({input_name: speech_inputs}) self.assertTrue(all(len(__lowercase) == len(__lowercase) for x, y in zip(__lowercase , processed_features[input_name]))) __UpperCamelCase :Any = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__lowercase) __UpperCamelCase :Optional[int] = BatchFeature({input_name: speech_inputs} , tensor_type='''np''') __UpperCamelCase :Any = processed_features[input_name] if len(batch_features_input.shape) < 3: __UpperCamelCase :Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size)) @require_torch def UpperCamelCase__ ( self) -> int: __UpperCamelCase :Dict = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__lowercase) __UpperCamelCase :Tuple = self.feature_extraction_class(**self.feat_extract_dict) __UpperCamelCase :str = feat_extract.model_input_names[0] __UpperCamelCase :Optional[Any] = BatchFeature({input_name: speech_inputs} , tensor_type='''pt''') __UpperCamelCase :Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape) < 3: __UpperCamelCase :str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size)) @require_tf def UpperCamelCase__ ( self) -> Optional[Any]: __UpperCamelCase :str = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__lowercase) __UpperCamelCase :str = self.feature_extraction_class(**self.feat_extract_dict) __UpperCamelCase :Union[str, Any] = feat_extract.model_input_names[0] __UpperCamelCase :Optional[Any] = BatchFeature({input_name: speech_inputs} , tensor_type='''tf''') __UpperCamelCase :int = processed_features[input_name] if len(batch_features_input.shape) < 3: __UpperCamelCase :List[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size)) def UpperCamelCase__ ( self , __lowercase=False) -> Dict: def _inputs_have_equal_length(__lowercase): __UpperCamelCase :List[str] = len(input[0]) for input_slice in input[1:]: if len(__lowercase) != length: return False return True def _inputs_are_equal(__lowercase , __lowercase): if len(__lowercase) != len(__lowercase): return False for input_slice_a, input_slice_a in zip(__lowercase , __lowercase): if not np.allclose(np.asarray(__lowercase) , np.asarray(__lowercase) , atol=1E-3): return False return True __UpperCamelCase :List[str] = self.feature_extraction_class(**self.feat_extract_dict) __UpperCamelCase :Optional[int] = self.feat_extract_tester.prepare_inputs_for_common(numpify=__lowercase) __UpperCamelCase :Any = feat_extract.model_input_names[0] __UpperCamelCase :Optional[Any] = BatchFeature({input_name: speech_inputs}) __UpperCamelCase :Optional[Any] = self.feat_extract_tester.seq_length_diff __UpperCamelCase :Union[str, Any] = self.feat_extract_tester.max_seq_length + pad_diff __UpperCamelCase :Tuple = self.feat_extract_tester.min_seq_length __UpperCamelCase :Optional[int] = self.feat_extract_tester.batch_size __UpperCamelCase :Any = self.feat_extract_tester.feature_size # test padding for List[int] + numpy __UpperCamelCase :List[Any] = feat_extract.pad(__lowercase , padding=__lowercase) __UpperCamelCase :Tuple = input_a[input_name] __UpperCamelCase :int = feat_extract.pad(__lowercase , padding='''longest''') __UpperCamelCase :int = input_a[input_name] __UpperCamelCase :Optional[Any] = feat_extract.pad(__lowercase , padding='''max_length''' , max_length=len(speech_inputs[-1])) __UpperCamelCase :Dict = input_a[input_name] __UpperCamelCase :List[Any] = feat_extract.pad(__lowercase , padding='''longest''' , return_tensors='''np''') __UpperCamelCase :Optional[int] = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(__lowercase): feat_extract.pad(__lowercase , padding='''max_length''')[input_name] __UpperCamelCase :Any = feat_extract.pad( __lowercase , padding='''max_length''' , max_length=__lowercase , return_tensors='''np''') __UpperCamelCase :Tuple = input_a[input_name] self.assertFalse(_inputs_have_equal_length(__lowercase)) self.assertTrue(_inputs_have_equal_length(__lowercase)) self.assertTrue(_inputs_have_equal_length(__lowercase)) self.assertTrue(_inputs_are_equal(__lowercase , __lowercase)) self.assertTrue(len(input_a[0]) == pad_min_length) self.assertTrue(len(input_a[1]) == pad_min_length + pad_diff) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0]))) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length)) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size) # test padding for `pad_to_multiple_of` for List[int] + numpy __UpperCamelCase :int = feat_extract.pad(__lowercase , pad_to_multiple_of=10) __UpperCamelCase :Tuple = input_a[input_name] __UpperCamelCase :Optional[int] = feat_extract.pad(__lowercase , padding='''longest''' , pad_to_multiple_of=10) __UpperCamelCase :Tuple = input_a[input_name] __UpperCamelCase :str = feat_extract.pad( __lowercase , padding='''max_length''' , pad_to_multiple_of=10 , max_length=__lowercase) __UpperCamelCase :Any = input_a[input_name] __UpperCamelCase :List[str] = feat_extract.pad( __lowercase , padding='''max_length''' , pad_to_multiple_of=10 , max_length=__lowercase , return_tensors='''np''' , ) __UpperCamelCase :List[str] = input_a[input_name] self.assertTrue(all(len(__lowercase) % 10 == 0 for x in input_a)) self.assertTrue(_inputs_are_equal(__lowercase , __lowercase)) __UpperCamelCase :str = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(__lowercase) == expected_mult_pad_length for x in input_a)) self.assertEqual(input_a.shape[:2] , (batch_size, expected_mult_pad_length)) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size) # Check padding value is correct __UpperCamelCase :Optional[Any] = (np.ones(self.feat_extract_tester.feature_size) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0])[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)) < 1E-3) self.assertTrue( abs( np.asarray(input_a[1])[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff)) < 1E-3) self.assertTrue( abs( np.asarray(input_a[2])[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff)) < 1E-3) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)) < 1E-3) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length)) < 1E-3) def UpperCamelCase__ ( self , __lowercase=False) -> Dict: def _inputs_have_equal_length(__lowercase): __UpperCamelCase :Dict = len(input[0]) for input_slice in input[1:]: if len(__lowercase) != length: return False return True def _inputs_are_equal(__lowercase , __lowercase): if len(__lowercase) != len(__lowercase): return False for input_slice_a, input_slice_a in zip(__lowercase , __lowercase): if not np.allclose(np.asarray(__lowercase) , np.asarray(__lowercase) , atol=1E-3): return False return True __UpperCamelCase :str = self.feature_extraction_class(**self.feat_extract_dict) __UpperCamelCase :Union[str, Any] = self.feat_extract_tester.prepare_inputs_for_common(numpify=__lowercase) __UpperCamelCase :Tuple = feat_extract.model_input_names[0] __UpperCamelCase :Dict = BatchFeature({input_name: speech_inputs}) # truncate to smallest __UpperCamelCase :List[Any] = feat_extract.pad( __lowercase , padding='''max_length''' , max_length=len(speech_inputs[0]) , truncation=__lowercase) __UpperCamelCase :str = input_a[input_name] __UpperCamelCase :Optional[int] = feat_extract.pad(__lowercase , padding='''max_length''' , max_length=len(speech_inputs[0])) __UpperCamelCase :List[str] = input_a[input_name] self.assertTrue(_inputs_have_equal_length(__lowercase)) self.assertFalse(_inputs_have_equal_length(__lowercase)) # truncate to smallest with np __UpperCamelCase :Union[str, Any] = feat_extract.pad( __lowercase , padding='''max_length''' , max_length=len(speech_inputs[0]) , return_tensors='''np''' , truncation=__lowercase , ) __UpperCamelCase :List[Any] = input_a[input_name] __UpperCamelCase :int = feat_extract.pad( __lowercase , padding='''max_length''' , max_length=len(speech_inputs[0]) , return_tensors='''np''') __UpperCamelCase :Optional[Any] = input_a[input_name] self.assertTrue(_inputs_have_equal_length(__lowercase)) self.assertTrue(input_a.shape[1] == len(speech_inputs[0])) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(__lowercase)) # truncate to middle __UpperCamelCase :Optional[Any] = feat_extract.pad( __lowercase , padding='''max_length''' , max_length=len(speech_inputs[1]) , truncation=__lowercase , return_tensors='''np''' , ) __UpperCamelCase :Dict = input_a[input_name] __UpperCamelCase :str = feat_extract.pad( __lowercase , padding='''max_length''' , max_length=len(speech_inputs[1]) , truncation=__lowercase) __UpperCamelCase :Union[str, Any] = input_a[input_name] __UpperCamelCase :Optional[Any] = feat_extract.pad( __lowercase , padding='''max_length''' , max_length=len(speech_inputs[1]) , return_tensors='''np''') __UpperCamelCase :Union[str, Any] = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1])) self.assertTrue(_inputs_have_equal_length(__lowercase)) self.assertTrue(_inputs_have_equal_length(__lowercase)) self.assertTrue(_inputs_are_equal(__lowercase , __lowercase)) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(__lowercase)) self.assertTrue(len(input_a[-1]) == len(speech_inputs[-1])) # padding has to be max_length when setting `truncation=True` with self.assertRaises(__lowercase): feat_extract.pad(__lowercase , truncation=__lowercase)[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(__lowercase): feat_extract.pad(__lowercase , padding='''longest''' , truncation=__lowercase)[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(__lowercase): feat_extract.pad(__lowercase , padding='''longest''' , truncation=__lowercase)[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(__lowercase): feat_extract.pad(__lowercase , padding='''max_length''' , truncation=__lowercase)[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy __UpperCamelCase :Dict = 12 __UpperCamelCase :str = feat_extract.pad( __lowercase , padding='''max_length''' , max_length=len(speech_inputs[0]) , pad_to_multiple_of=__lowercase , truncation=__lowercase , ) __UpperCamelCase :List[Any] = input_a[input_name] __UpperCamelCase :Tuple = feat_extract.pad( __lowercase , padding='''max_length''' , max_length=len(speech_inputs[0]) , pad_to_multiple_of=__lowercase , ) __UpperCamelCase :Any = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of __UpperCamelCase :Optional[Any] = len(speech_inputs[0]) if expected_length % pad_to_multiple_of != 0: __UpperCamelCase :Dict = ((len(speech_inputs[0]) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0]) == expected_length) self.assertTrue(_inputs_have_equal_length(__lowercase)) self.assertFalse(_inputs_have_equal_length(__lowercase)) def UpperCamelCase__ ( self) -> Any: self._check_padding(numpify=__lowercase) def UpperCamelCase__ ( self) -> Dict: self._check_padding(numpify=__lowercase) def UpperCamelCase__ ( self) -> Any: self._check_truncation(numpify=__lowercase) def UpperCamelCase__ ( self) -> Union[str, Any]: self._check_truncation(numpify=__lowercase) @require_torch def UpperCamelCase__ ( self) -> Tuple: __UpperCamelCase :int = self.feature_extraction_class(**self.feat_extract_dict) __UpperCamelCase :Union[str, Any] = self.feat_extract_tester.prepare_inputs_for_common() __UpperCamelCase :str = feat_extract.model_input_names[0] __UpperCamelCase :int = BatchFeature({input_name: speech_inputs}) __UpperCamelCase :List[str] = feat_extract.pad(__lowercase , padding='''longest''' , return_tensors='''np''')[input_name] __UpperCamelCase :List[Any] = feat_extract.pad(__lowercase , padding='''longest''' , return_tensors='''pt''')[input_name] self.assertTrue(abs(input_np.astype(np.floataa).sum() - input_pt.numpy().astype(np.floataa).sum()) < 1E-2) @require_tf def UpperCamelCase__ ( self) -> Tuple: __UpperCamelCase :int = self.feature_extraction_class(**self.feat_extract_dict) __UpperCamelCase :Any = self.feat_extract_tester.prepare_inputs_for_common() __UpperCamelCase :Any = feat_extract.model_input_names[0] __UpperCamelCase :Union[str, Any] = BatchFeature({input_name: speech_inputs}) __UpperCamelCase :str = feat_extract.pad(__lowercase , padding='''longest''' , return_tensors='''np''')[input_name] __UpperCamelCase :Optional[Any] = feat_extract.pad(__lowercase , padding='''longest''' , return_tensors='''tf''')[input_name] self.assertTrue(abs(input_np.astype(np.floataa).sum() - input_tf.numpy().astype(np.floataa).sum()) < 1E-2) def UpperCamelCase__ ( self) -> str: __UpperCamelCase :List[Any] = self.feat_extract_dict __UpperCamelCase :Dict = True __UpperCamelCase :Dict = self.feature_extraction_class(**__lowercase) __UpperCamelCase :List[Any] = self.feat_extract_tester.prepare_inputs_for_common() __UpperCamelCase :Any = [len(__lowercase) for x in speech_inputs] __UpperCamelCase :int = feat_extract.model_input_names[0] __UpperCamelCase :Optional[int] = BatchFeature({input_name: speech_inputs}) __UpperCamelCase :Union[str, Any] = feat_extract.pad(__lowercase , padding='''longest''' , return_tensors='''np''') self.assertIn('''attention_mask''' , __lowercase) self.assertListEqual(list(processed.attention_mask.shape) , list(processed[input_name].shape[:2])) self.assertListEqual(processed.attention_mask.sum(-1).tolist() , __lowercase) def UpperCamelCase__ ( self) -> List[str]: __UpperCamelCase :Optional[int] = self.feat_extract_dict __UpperCamelCase :Optional[int] = True __UpperCamelCase :Dict = self.feature_extraction_class(**__lowercase) __UpperCamelCase :List[str] = self.feat_extract_tester.prepare_inputs_for_common() __UpperCamelCase :List[Any] = [len(__lowercase) for x in speech_inputs] __UpperCamelCase :List[Any] = feat_extract.model_input_names[0] __UpperCamelCase :int = BatchFeature({input_name: speech_inputs}) __UpperCamelCase :Dict = min(__lowercase) __UpperCamelCase :Union[str, Any] = feat_extract.pad( __lowercase , padding='''max_length''' , max_length=__lowercase , truncation=__lowercase , return_tensors='''np''') self.assertIn('''attention_mask''' , __lowercase) self.assertListEqual( list(processed_pad.attention_mask.shape) , [processed_pad[input_name].shape[0], max_length]) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1).tolist() , [max_length for x in speech_inputs])
452
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: lowerCamelCase_ : List[Any] = None lowerCamelCase_ : str = logging.get_logger(__name__) lowerCamelCase_ : Optional[int] = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase_ : Optional[Any] = { """vocab_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model""", }, """tokenizer_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/tokenizer.json""", }, } lowerCamelCase_ : Any = { """camembert-base""": 512, } lowerCamelCase_ : Dict = """▁""" class a__ ( __snake_case ): A__ : Tuple = VOCAB_FILES_NAMES A__ : List[str] = PRETRAINED_VOCAB_FILES_MAP A__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : List[Any] = ['input_ids', 'attention_mask'] A__ : Any = CamembertTokenizer def __init__( self , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase="<s>" , UpperCAmelCase="</s>" , UpperCAmelCase="</s>" , UpperCAmelCase="<s>" , UpperCAmelCase="<unk>" , UpperCAmelCase="<pad>" , UpperCAmelCase="<mask>" , UpperCAmelCase=["<s>NOTUSED", "</s>NOTUSED"] , **UpperCAmelCase , ) -> List[Any]: # Mask token behave like a normal word, i.e. include the space before it __a = AddedToken(UpperCAmelCase , lstrip=UpperCAmelCase , rstrip=UpperCAmelCase ) if isinstance(UpperCAmelCase , UpperCAmelCase ) else mask_token super().__init__( UpperCAmelCase , tokenizer_file=UpperCAmelCase , bos_token=UpperCAmelCase , eos_token=UpperCAmelCase , sep_token=UpperCAmelCase , cls_token=UpperCAmelCase , unk_token=UpperCAmelCase , pad_token=UpperCAmelCase , mask_token=UpperCAmelCase , additional_special_tokens=UpperCAmelCase , **UpperCAmelCase , ) __a = vocab_file __a = False if not self.vocab_file else True def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase = None ) -> List[int]: 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 __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase = None ) -> List[int]: __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(UpperCAmelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a = os.path.join( UpperCAmelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase ): copyfile(self.vocab_file , UpperCAmelCase ) return (out_vocab_file,)
559
def lowerCAmelCase( __lowerCamelCase , __lowerCamelCase = 0 ): __a = length or len(__lowerCamelCase ) __a = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: __a , __a = list_data[i + 1], list_data[i] __a = True return list_data if not swapped else bubble_sort(__lowerCamelCase , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
559
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
403
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def __SCREAMING_SNAKE_CASE ( UpperCamelCase : Tuple ) -> Tuple: """simple docstring""" if isinstance(UpperCamelCase , collections.abc.Iterable ): return x return (x, x) @require_flax class lowerCamelCase_ : def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): pass def __magic_name__ ( self ): pass def __magic_name__ ( self ): pass def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a_ = np.abs((a - b) ).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , f"""Difference between torch and flax is {diff} (>= {tol}).""" ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): a_ = VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) a_ = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], config.projection_dim) ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): a_ , a_ = self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = {"""vision_model""": vision_model, """text_model""": text_model} a_ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE ) a_ = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): a_ , a_ = self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = {"""vision_model""": vision_model, """text_model""": text_model} a_ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE ) a_ = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) a_ = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE ) a_ = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) a_ = after_output[0] a_ = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-3 ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): a_ , a_ = self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = {"""vision_model""": vision_model, """text_model""": text_model} a_ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE ) a_ = model( input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) a_ = output.vision_model_output.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) a_ = to_atuple(vision_model.config.image_size ) a_ = to_atuple(vision_model.config.patch_size ) a_ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) a_ = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) a_ = output.text_model_output.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): pt_model.to(_SCREAMING_SNAKE_CASE ) pt_model.eval() # prepare inputs a_ = inputs_dict a_ = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): a_ = pt_model(**_SCREAMING_SNAKE_CASE ).to_tuple() a_ = fx_model(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(_SCREAMING_SNAKE_CASE , pt_output.numpy() , 4E-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE ) a_ = fx_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(_SCREAMING_SNAKE_CASE , pt_output.numpy() , 4E-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_SCREAMING_SNAKE_CASE ) a_ = VisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_flax=_SCREAMING_SNAKE_CASE ) pt_model_loaded.to(_SCREAMING_SNAKE_CASE ) pt_model_loaded.eval() with torch.no_grad(): a_ = pt_model_loaded(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(_SCREAMING_SNAKE_CASE , pt_output_loaded.numpy() , 4E-2 ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a_ = VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) a_ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _SCREAMING_SNAKE_CASE ) a_ = fx_state self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a_ = VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) a_ = VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE ) a_ = load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , fx_model.params ) self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_SCREAMING_SNAKE_CASE ) def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_SCREAMING_SNAKE_CASE ) def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() self.check_save_load(**_SCREAMING_SNAKE_CASE ) def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_SCREAMING_SNAKE_CASE ) @is_pt_flax_cross_test def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() a_ = config_inputs_dict.pop("""vision_config""" ) a_ = config_inputs_dict.pop("""text_config""" ) a_ = config_inputs_dict self.check_equivalence_pt_to_flax(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.check_equivalence_flax_to_pt(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def __magic_name__ ( self ): a_ , a_ = self.get_pretrained_model_and_inputs() a_ = model_a(**_SCREAMING_SNAKE_CASE ) a_ = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_SCREAMING_SNAKE_CASE ) a_ = FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE ) a_ = model_a(**_SCREAMING_SNAKE_CASE ) a_ = after_outputs[0] a_ = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1E-5 ) @require_flax class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): def __magic_name__ ( self ): a_ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( """hf-internal-testing/tiny-random-vit""" , """hf-internal-testing/tiny-bert""" , vision_from_pt=_SCREAMING_SNAKE_CASE , text_from_pt=_SCREAMING_SNAKE_CASE , ) a_ = 13 a_ = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) a_ = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) a_ = random_attention_mask([batch_size, 4] ) a_ = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a_ = FlaxViTModel(_SCREAMING_SNAKE_CASE ) a_ = FlaxBertModel(_SCREAMING_SNAKE_CASE ) return vision_model, text_model def __magic_name__ ( self ): a_ = FlaxViTModelTester(self ) a_ = FlaxBertModelTester(self ) a_ = vit_model_tester.prepare_config_and_inputs() a_ = bert_model_tester.prepare_config_and_inputs() a_ , a_ = vision_config_and_inputs a_ , a_ , a_ , a_ = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): def __magic_name__ ( self ): a_ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( """hf-internal-testing/tiny-random-clip""" , """hf-internal-testing/tiny-bert""" , vision_from_pt=_SCREAMING_SNAKE_CASE , text_from_pt=_SCREAMING_SNAKE_CASE , ) a_ = 13 a_ = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) a_ = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) a_ = random_attention_mask([batch_size, 4] ) a_ = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a_ = FlaxCLIPVisionModel(_SCREAMING_SNAKE_CASE ) a_ = FlaxBertModel(_SCREAMING_SNAKE_CASE ) return vision_model, text_model def __magic_name__ ( self ): a_ = FlaxCLIPVisionModelTester(self ) a_ = FlaxBertModelTester(self ) a_ = clip_model_tester.prepare_config_and_inputs() a_ = bert_model_tester.prepare_config_and_inputs() a_ , a_ = vision_config_and_inputs a_ , a_ , a_ , a_ = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class lowerCamelCase_ ( unittest.TestCase ): @slow def __magic_name__ ( self ): a_ = FlaxVisionTextDualEncoderModel.from_pretrained("""clip-italian/clip-italian""" , logit_scale_init_value=1.0 ) a_ = VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian""" ) a_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) a_ = processor( text=["""una foto di un gatto""", """una foto di un cane"""] , images=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="""np""" ) a_ = model(**_SCREAMING_SNAKE_CASE ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) a_ = np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]] ) self.assertTrue(np.allclose(outputs.logits_per_image , _SCREAMING_SNAKE_CASE , atol=1E-3 ) )
403
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase : str = { "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class SCREAMING_SNAKE_CASE__ ( snake_case_ ): lowercase__ = '''nllb-moe''' lowercase__ = ['''past_key_values'''] lowercase__ = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self : Dict , lowerCAmelCase_ : List[Any]=1_2_8_1_1_2 , lowerCAmelCase_ : Optional[Any]=1_0_2_4 , lowerCAmelCase_ : Any=1_2 , lowerCAmelCase_ : int=4_0_9_6 , lowerCAmelCase_ : Any=1_6 , lowerCAmelCase_ : List[Any]=1_2 , lowerCAmelCase_ : int=4_0_9_6 , lowerCAmelCase_ : Dict=1_6 , lowerCAmelCase_ : Any=0.05 , lowerCAmelCase_ : Optional[Any]=0.05 , lowerCAmelCase_ : Tuple=True , lowerCAmelCase_ : Tuple=True , lowerCAmelCase_ : Any="relu" , lowerCAmelCase_ : Optional[int]=1_0_2_4 , lowerCAmelCase_ : List[str]=0.1 , lowerCAmelCase_ : int=0.1 , lowerCAmelCase_ : Union[str, Any]=0.0 , lowerCAmelCase_ : Dict=0.02 , lowerCAmelCase_ : Optional[int]=2 , lowerCAmelCase_ : Optional[int]=True , lowerCAmelCase_ : str=False , lowerCAmelCase_ : Any="float32" , lowerCAmelCase_ : str=False , lowerCAmelCase_ : str=1_2_8 , lowerCAmelCase_ : Union[str, Any]=6_4 , lowerCAmelCase_ : int=4 , lowerCAmelCase_ : List[Any]=4 , lowerCAmelCase_ : Optional[Any]=0.001 , lowerCAmelCase_ : Union[str, Any]=0.001 , lowerCAmelCase_ : Tuple="all" , lowerCAmelCase_ : Tuple=False , lowerCAmelCase_ : int=False , lowerCAmelCase_ : Any=1.0 , lowerCAmelCase_ : int=0.2 , lowerCAmelCase_ : Optional[Any]=1 , lowerCAmelCase_ : Dict=0 , lowerCAmelCase_ : Any=2 , lowerCAmelCase_ : Any=False , **lowerCAmelCase_ : int , ): """simple docstring""" lowercase_ = vocab_size lowercase_ = max_position_embeddings lowercase_ = d_model lowercase_ = encoder_ffn_dim lowercase_ = encoder_layers lowercase_ = encoder_attention_heads lowercase_ = decoder_ffn_dim lowercase_ = decoder_layers lowercase_ = decoder_attention_heads lowercase_ = dropout lowercase_ = attention_dropout lowercase_ = activation_dropout lowercase_ = activation_function lowercase_ = init_std lowercase_ = encoder_layerdrop lowercase_ = decoder_layerdrop lowercase_ = use_cache lowercase_ = encoder_layers lowercase_ = scale_embedding # scale factor will be sqrt(d_model) if True lowercase_ = router_z_loss_coef lowercase_ = router_aux_loss_coef lowercase_ = decoder_sparse_step lowercase_ = encoder_sparse_step lowercase_ = num_experts lowercase_ = expert_capacity lowercase_ = router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}''') lowercase_ = router_dtype lowercase_ = router_ignore_padding_tokens lowercase_ = batch_prioritized_routing lowercase_ = second_expert_policy lowercase_ = normalize_router_prob_before_dropping lowercase_ = moe_eval_capacity_token_fraction lowercase_ = moe_token_dropout lowercase_ = output_router_logits super().__init__( pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , is_encoder_decoder=UpperCAmelCase__ , decoder_start_token_id=UpperCAmelCase__ , **UpperCAmelCase__ , )
567
"""simple docstring""" def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) _a : Tuple = str(bin(UpperCamelCase__ ) )[2:] # remove the leading "0b" _a : Optional[Any] = str(bin(UpperCamelCase__ ) )[2:] # remove the leading "0b" _a : List[str] = max(len(UpperCamelCase__ ) , len(UpperCamelCase__ ) ) return "0b" + "".join( str(int(char_a == """1""" and char_b == """1""" ) ) for char_a, char_b in zip(a_binary.zfill(UpperCamelCase__ ) , b_binary.zfill(UpperCamelCase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
389
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ = { """configuration_lilt""": ["""LILT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LiltConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ """LILT_PRETRAINED_MODEL_ARCHIVE_LIST""", """LiltForQuestionAnswering""", """LiltForSequenceClassification""", """LiltForTokenClassification""", """LiltModel""", """LiltPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys a__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
702
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a__ = { """configuration_clip""": [ """CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CLIPConfig""", """CLIPOnnxConfig""", """CLIPTextConfig""", """CLIPVisionConfig""", ], """processing_clip""": ["""CLIPProcessor"""], """tokenization_clip""": ["""CLIPTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = ["""CLIPTokenizerFast"""] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = ["""CLIPFeatureExtractor"""] a__ = ["""CLIPImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ """CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """CLIPModel""", """CLIPPreTrainedModel""", """CLIPTextModel""", """CLIPTextModelWithProjection""", """CLIPVisionModel""", """CLIPVisionModelWithProjection""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ """TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFCLIPModel""", """TFCLIPPreTrainedModel""", """TFCLIPTextModel""", """TFCLIPVisionModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ """FlaxCLIPModel""", """FlaxCLIPPreTrainedModel""", """FlaxCLIPTextModel""", """FlaxCLIPTextPreTrainedModel""", """FlaxCLIPVisionModel""", """FlaxCLIPVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys a__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
99
0
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse("1.6"): __lowerCamelCase : str = True from torch.cuda.amp import autocast __lowerCamelCase : List[str] = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( snake_case_=None, snake_case_=None ) -> List[Any]: return field(default_factory=lambda: default, metadata=A__ ) @dataclass class a : __lowercase = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) __lowercase = field( default=__UpperCAmelCase ,metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} ,) __lowercase = field( default=__UpperCAmelCase ,metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""} ) __lowercase = field( default=0.1 ,metadata={"""help""": """The dropout ratio for the attention probabilities."""} ) __lowercase = field( default=0.1 ,metadata={"""help""": """The dropout ratio for activations inside the fully connected layer."""} ) __lowercase = field( default=0.1 ,metadata={ """help""": """The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.""" } ,) __lowercase = field( default=0.1 ,metadata={"""help""": """The dropout probabilitiy for all 1D convolutional layers in feature extractor."""} ,) __lowercase = field( default=0.05 ,metadata={ """help""": ( """Propability of each feature vector along the time axis to be chosen as the start of the vector""" """span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature""" """vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.""" ) } ,) __lowercase = field(default=0.0 ,metadata={"""help""": """The LayerDrop probability."""} ) @dataclass class a : __lowercase = field( default=__UpperCAmelCase ,metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) __lowercase = field( default="""train+validation""" ,metadata={ """help""": """The name of the training data set split to use (via the datasets library). Defaults to \'train\'""" } ,) __lowercase = field( default=__UpperCAmelCase ,metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""} ) __lowercase = field( default=__UpperCAmelCase ,metadata={"""help""": """The number of processes to use for the preprocessing."""} ,) __lowercase = field( default=__UpperCAmelCase ,metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } ,) __lowercase = field( default=__UpperCAmelCase ,metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of validation examples to this """ """value if set.""" ) } ,) __lowercase = list_field( default=[""",""", """?""", """.""", """!""", """-""", """;""", """:""", """\"\"""", """%""", """\'""", """\"""", """�"""] ,metadata={"""help""": """A list of characters to remove from the transcripts."""} ,) @dataclass class a : __lowercase = 42 __lowercase = True __lowercase = None __lowercase = None __lowercase = None __lowercase = None def __call__( self , __UpperCamelCase )-> Dict[str, torch.Tensor]: '''simple docstring''' A__ : Optional[int] =[{'input_values': feature['input_values']} for feature in features] A__ : Dict =[{'input_ids': feature['labels']} for feature in features] A__ : Tuple =self.processor.pad( __UpperCamelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) A__ : str =self.processor.pad( labels=__UpperCamelCase , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors='''pt''' , ) # replace padding with -100 to ignore loss correctly A__ : int =labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1 ) , -1_00 ) A__ : Any =labels return batch class a ( __UpperCAmelCase ): def lowerCAmelCase_ ( self , __UpperCamelCase , __UpperCamelCase )-> torch.Tensor: '''simple docstring''' model.train() A__ : Any =self._prepare_inputs(__UpperCamelCase ) if self.use_amp: with autocast(): A__ : Dict =self.compute_loss(__UpperCamelCase , __UpperCamelCase ) else: A__ : List[str] =self.compute_loss(__UpperCamelCase , __UpperCamelCase ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": A__ : Any =loss.mean() elif model.module.config.ctc_loss_reduction == "sum": A__ : Optional[int] =loss.sum() / (inputs['labels'] >= 0).sum() else: raise ValueError(F'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']' ) if self.args.gradient_accumulation_steps > 1: A__ : Optional[int] =loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(__UpperCamelCase ).backward() elif self.use_apex: with amp.scale_loss(__UpperCamelCase , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(__UpperCamelCase ) else: loss.backward() return loss.detach() def SCREAMING_SNAKE_CASE__ ( ) -> List[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__ : int =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. A__ : Tuple =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: A__ : List[Any] =parser.parse_args_into_dataclasses() # Detecting last checkpoint. A__ : Union[str, Any] =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: A__ : Union[str, Any] =get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. ' '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None: logger.info( f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', handlers=[logging.StreamHandler(sys.stdout )], ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''', A__ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: A__ : str =datasets.load_dataset( '''common_voice''', data_args.dataset_config_name, split=data_args.train_split_name ) A__ : Dict =datasets.load_dataset('''common_voice''', data_args.dataset_config_name, split='''test''' ) # Create and save tokenizer A__ : Optional[int] =f'[{"".join(data_args.chars_to_ignore )}]' def remove_special_characters(snake_case_ ): A__ : Union[str, Any] =re.sub(A__, '''''', batch['''sentence'''] ).lower() + ' ' return batch A__ : Union[str, Any] =train_dataset.map(A__, remove_columns=['''sentence'''] ) A__ : str =eval_dataset.map(A__, remove_columns=['''sentence'''] ) def extract_all_chars(snake_case_ ): A__ : Tuple =' '.join(batch['''text'''] ) A__ : Any =list(set(A__ ) ) return {"vocab": [vocab], "all_text": [all_text]} A__ : Tuple =train_dataset.map( A__, batched=A__, batch_size=-1, keep_in_memory=A__, remove_columns=train_dataset.column_names, ) A__ : Any =train_dataset.map( A__, batched=A__, batch_size=-1, keep_in_memory=A__, remove_columns=eval_dataset.column_names, ) A__ : Optional[Any] =list(set(vocab_train['''vocab'''][0] ) | set(vocab_test['''vocab'''][0] ) ) A__ : List[str] ={v: k for k, v in enumerate(A__ )} A__ : List[str] =vocab_dict[' '] del vocab_dict[" "] A__ : Tuple =len(A__ ) A__ : Dict =len(A__ ) with open('''vocab.json''', '''w''' ) as vocab_file: json.dump(A__, A__ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. A__ : str =WavaVecaCTCTokenizer( '''vocab.json''', unk_token='''[UNK]''', pad_token='''[PAD]''', word_delimiter_token='''|''', ) A__ : Any =WavaVecaFeatureExtractor( feature_size=1, sampling_rate=1_6_0_0_0, padding_value=0.0, do_normalize=A__, return_attention_mask=A__ ) A__ : int =WavaVecaProcessor(feature_extractor=A__, tokenizer=A__ ) A__ : List[Any] =WavaVecaForCTC.from_pretrained( model_args.model_name_or_path, cache_dir=model_args.cache_dir, activation_dropout=model_args.activation_dropout, attention_dropout=model_args.attention_dropout, hidden_dropout=model_args.hidden_dropout, feat_proj_dropout=model_args.feat_proj_dropout, mask_time_prob=model_args.mask_time_prob, gradient_checkpointing=training_args.gradient_checkpointing, layerdrop=model_args.layerdrop, ctc_loss_reduction='''mean''', pad_token_id=processor.tokenizer.pad_token_id, vocab_size=len(processor.tokenizer ), ) if data_args.max_train_samples is not None: A__ : Any =min(len(A__ ), data_args.max_train_samples ) A__ : Any =train_dataset.select(range(A__ ) ) if data_args.max_val_samples is not None: A__ : List[str] =eval_dataset.select(range(data_args.max_val_samples ) ) A__ : List[str] =torchaudio.transforms.Resample(4_8_0_0_0, 1_6_0_0_0 ) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(snake_case_ ): A__ : Optional[int] =torchaudio.load(batch['''path'''] ) A__ : Tuple =resampler(A__ ).squeeze().numpy() A__ : Any =1_6_0_0_0 A__ : int =batch['text'] return batch A__ : Dict =train_dataset.map( A__, remove_columns=train_dataset.column_names, num_proc=data_args.preprocessing_num_workers, ) A__ : List[Any] =eval_dataset.map( A__, remove_columns=eval_dataset.column_names, num_proc=data_args.preprocessing_num_workers, ) def prepare_dataset(snake_case_ ): # check that all files have the correct sampling rate assert ( len(set(batch['''sampling_rate'''] ) ) == 1 ), f'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.' A__ : Tuple =processor( audio=batch['''speech'''], text=batch['''target_text'''], sampling_rate=batch['''sampling_rate'''][0] ) batch.update(A__ ) return batch A__ : int =train_dataset.map( A__, remove_columns=train_dataset.column_names, batch_size=training_args.per_device_train_batch_size, batched=A__, num_proc=data_args.preprocessing_num_workers, ) A__ : Any =eval_dataset.map( A__, remove_columns=eval_dataset.column_names, batch_size=training_args.per_device_train_batch_size, batched=A__, num_proc=data_args.preprocessing_num_workers, ) # Metric A__ : int =datasets.load_metric('''wer''' ) def compute_metrics(snake_case_ ): A__ : Optional[Any] =pred.predictions A__ : int =np.argmax(A__, axis=-1 ) A__ : Any =processor.tokenizer.pad_token_id A__ : int =processor.batch_decode(A__ ) # we do not want to group tokens when computing the metrics A__ : Tuple =processor.batch_decode(pred.label_ids, group_tokens=A__ ) A__ : Union[str, Any] =wer_metric.compute(predictions=A__, references=A__ ) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator A__ : Any =DataCollatorCTCWithPadding(processor=A__, padding=A__ ) # Initialize our Trainer A__ : List[Any] =CTCTrainer( model=A__, data_collator=A__, args=A__, compute_metrics=A__, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, tokenizer=processor.feature_extractor, ) # Training if training_args.do_train: if last_checkpoint is not None: A__ : str =last_checkpoint elif os.path.isdir(model_args.model_name_or_path ): A__ : Union[str, Any] =model_args.model_name_or_path else: A__ : Optional[Any] =None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank ): processor.save_pretrained(training_args.output_dir ) A__ : List[str] =trainer.train(resume_from_checkpoint=A__ ) trainer.save_model() A__ : Dict =train_result.metrics A__ : List[Any] =( data_args.max_train_samples if data_args.max_train_samples is not None else len(A__ ) ) A__ : List[Any] =min(A__, len(A__ ) ) trainer.log_metrics('''train''', A__ ) trainer.save_metrics('''train''', A__ ) trainer.save_state() # Evaluation A__ : Tuple ={} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) A__ : Dict =trainer.evaluate() A__ : Tuple =data_args.max_val_samples if data_args.max_val_samples is not None else len(A__ ) A__ : Any =min(A__, len(A__ ) ) trainer.log_metrics('''eval''', A__ ) trainer.save_metrics('''eval''', A__ ) return results if __name__ == "__main__": main()
416
import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class A__ ( __UpperCAmelCase ): """simple docstring""" def __init__( self , lowercase = "▁" , lowercase = True , lowercase = "<unk>" , lowercase = "</s>" , lowercase = "<pad>" , ) -> str: '''simple docstring''' a__ : Optional[Any] = { 'pad': {'id': 0, 'token': pad_token}, 'eos': {'id': 1, 'token': eos_token}, 'unk': {'id': 2, 'token': unk_token}, } a__ : List[str] = [None] * len(self.special_tokens) for token_dict in self.special_tokens.values(): a__ : Union[str, Any] = token_dict['token'] a__ : Any = Tokenizer(Unigram()) a__ : Any = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(' {2,}') , ' '), normalizers.Lowercase(), ]) a__ : Optional[int] = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=lowercase , add_prefix_space=lowercase), pre_tokenizers.Digits(individual_digits=lowercase), pre_tokenizers.Punctuation(), ]) a__ : Dict = decoders.Metaspace(replacement=lowercase , add_prefix_space=lowercase) a__ : int = TemplateProcessing( single=F'$A {self.special_tokens["eos"]["token"]}' , special_tokens=[(self.special_tokens['eos']['token'], self.special_tokens['eos']['id'])] , ) a__ : str = { 'model': 'SentencePieceUnigram', 'replacement': replacement, 'add_prefix_space': add_prefix_space, } super().__init__(lowercase , lowercase) def __lowercase ( self , lowercase , lowercase = 8000 , lowercase = True , ) -> Any: '''simple docstring''' a__ : int = trainers.UnigramTrainer( vocab_size=lowercase , special_tokens=self.special_tokens_list , show_progress=lowercase , ) if isinstance(lowercase , lowercase): a__ : List[Any] = [files] self._tokenizer.train(lowercase , trainer=lowercase) self.add_unk_id() def __lowercase ( self , lowercase , lowercase = 8000 , lowercase = True , ) -> Dict: '''simple docstring''' a__ : str = trainers.UnigramTrainer( vocab_size=lowercase , special_tokens=self.special_tokens_list , show_progress=lowercase , ) self._tokenizer.train_from_iterator(lowercase , trainer=lowercase) self.add_unk_id() def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : List[str] = json.loads(self._tokenizer.to_str()) a__ : List[Any] = self.special_tokens['unk']['id'] a__ : str = Tokenizer.from_str(json.dumps(lowercase))
302
0
# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class lowerCamelCase_ ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase = 42 __UpperCAmelCase = None def lowercase_ ( _UpperCamelCase , _UpperCamelCase=0.999 , _UpperCamelCase="cosine" , ): '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(_UpperCamelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_UpperCamelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) __lowercase = [] for i in range(_UpperCamelCase ): __lowercase = i / num_diffusion_timesteps __lowercase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_UpperCamelCase ) / alpha_bar_fn(_UpperCamelCase ) , _UpperCamelCase ) ) return torch.tensor(_UpperCamelCase , dtype=torch.floataa ) class lowerCamelCase_ ( lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase = 1 @register_to_config def __init__( self , snake_case_ = 1_0_0_0 , snake_case_ = 0.0_0_0_1 , snake_case_ = 0.0_2 , snake_case_ = "linear" , snake_case_ = None , snake_case_ = True , snake_case_ = True , snake_case_ = 0 , snake_case_ = "epsilon" , snake_case_ = 1.0 , **snake_case_ , ) -> Any: '''simple docstring''' if kwargs.get('''set_alpha_to_one''' , snake_case_ ) is not None: __lowercase = ( '''The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.''' ) deprecate('''set_alpha_to_one''' , '''1.0.0''' , snake_case_ , standard_warn=snake_case_ ) __lowercase = kwargs['''set_alpha_to_one'''] if trained_betas is not None: __lowercase = torch.tensor(snake_case_ , dtype=torch.floataa ) elif beta_schedule == "linear": __lowercase = torch.linspace(snake_case_ , snake_case_ , snake_case_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __lowercase = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , snake_case_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __lowercase = betas_for_alpha_bar(snake_case_ ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) __lowercase = 1.0 - self.betas __lowercase = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. __lowercase = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution __lowercase = 1.0 # setable values __lowercase = None __lowercase = torch.from_numpy(np.arange(0 , snake_case_ ).copy().astype(np.intaa ) ) def A ( self , snake_case_ , snake_case_ = None ) -> torch.FloatTensor: '''simple docstring''' return sample def A ( self , snake_case_ , snake_case_ = None ) -> int: '''simple docstring''' if num_inference_steps > self.config.num_train_timesteps: raise ValueError( F'`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:' F' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle' F' maximal {self.config.num_train_timesteps} timesteps.' ) __lowercase = num_inference_steps __lowercase = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __lowercase = (np.arange(0 , snake_case_ ) * step_ratio).round().copy().astype(np.intaa ) __lowercase = torch.from_numpy(snake_case_ ).to(snake_case_ ) self.timesteps += self.config.steps_offset def A ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ = 0.0 , snake_case_ = False , snake_case_ = None , snake_case_ = True , ) -> Union[DDIMSchedulerOutput, Tuple]: '''simple docstring''' __lowercase = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process __lowercase = self.alphas_cumprod[timestep] __lowercase = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) __lowercase = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": __lowercase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 __lowercase = model_output elif self.config.prediction_type == "sample": __lowercase = model_output __lowercase = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": __lowercase = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output __lowercase = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or' ''' `v_prediction`''' ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: __lowercase = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __lowercase = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __lowercase = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=snake_case_ , pred_original_sample=snake_case_ ) def __len__( self ) -> Any: '''simple docstring''' return self.config.num_train_timesteps
527
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCamelCase_ ( lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase = FlaxAutoencoderKL @property def A ( self ) -> Optional[int]: '''simple docstring''' __lowercase = 4 __lowercase = 3 __lowercase = (3_2, 3_2) __lowercase = jax.random.PRNGKey(0 ) __lowercase = jax.random.uniform(snake_case_ , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def A ( self ) -> Any: '''simple docstring''' __lowercase = { '''block_out_channels''': [3_2, 6_4], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 4, } __lowercase = self.dummy_input return init_dict, inputs_dict
527
1
import os # Precomputes a list of the 100 first triangular numbers __A = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def lowerCAmelCase_ ( ) -> List[str]: """simple docstring""" lowerCamelCase__: Optional[Any] =os.path.dirname(os.path.realpath(__a ) ) lowerCamelCase__: Optional[int] =os.path.join(__a , "words.txt" ) lowerCamelCase__: Dict ="" with open(__a ) as f: lowerCamelCase__: int =f.readline() lowerCamelCase__: Any =[word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCamelCase__: Optional[Any] =[ word for word in [sum(ord(__a ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(__a ) if __name__ == "__main__": print(solution())
59
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCAmelCase__ = '''maskformer-swin''' UpperCAmelCase__ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : Optional[int] , lowercase__ : List[Any]=224 , lowercase__ : Optional[Any]=4 , lowercase__ : Optional[Any]=3 , lowercase__ : List[str]=96 , lowercase__ : Dict=[2, 2, 6, 2] , lowercase__ : Tuple=[3, 6, 12, 24] , lowercase__ : Optional[Any]=7 , lowercase__ : Any=4.0 , lowercase__ : List[str]=True , lowercase__ : Optional[int]=0.0 , lowercase__ : Dict=0.0 , lowercase__ : Tuple=0.1 , lowercase__ : Any="gelu" , lowercase__ : Union[str, Any]=False , lowercase__ : Optional[int]=0.0_2 , lowercase__ : Tuple=1e-5 , lowercase__ : Dict=None , lowercase__ : List[Any]=None , **lowercase__ : Optional[Any] , ) ->List[str]: '''simple docstring''' super().__init__(**lowercase__ ) _UpperCamelCase : List[Any] = image_size _UpperCamelCase : Any = patch_size _UpperCamelCase : Union[str, Any] = num_channels _UpperCamelCase : Dict = embed_dim _UpperCamelCase : List[Any] = depths _UpperCamelCase : str = len(lowercase__ ) _UpperCamelCase : List[Any] = num_heads _UpperCamelCase : str = window_size _UpperCamelCase : Optional[Any] = mlp_ratio _UpperCamelCase : Optional[Any] = qkv_bias _UpperCamelCase : str = hidden_dropout_prob _UpperCamelCase : List[Any] = attention_probs_dropout_prob _UpperCamelCase : Union[str, Any] = drop_path_rate _UpperCamelCase : str = hidden_act _UpperCamelCase : Any = use_absolute_embeddings _UpperCamelCase : Tuple = layer_norm_eps _UpperCamelCase : Union[str, Any] = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _UpperCamelCase : Dict = int(embed_dim * 2 ** (len(lowercase__ ) - 1) ) _UpperCamelCase : List[Any] = ["stem"] + [f'''stage{idx}''' for idx in range(1 , len(lowercase__ ) + 1 )] _UpperCamelCase , _UpperCamelCase : Optional[Any] = get_aligned_output_features_output_indices( out_features=lowercase__ , out_indices=lowercase__ , stage_names=self.stage_names )
435
0
'''simple docstring''' from math import ceil, sqrt def _a( UpperCamelCase__ : int = 1_0_0_0_0_0_0 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] =0 for outer_width in range(3, (limit // 4) + 2 ): if outer_width**2 > limit: SCREAMING_SNAKE_CASE__ : List[str] =max(ceil(sqrt(outer_width**2 - limit ) ), 1 ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] =1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(F'''{solution() = }''')
665
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __SCREAMING_SNAKE_CASE : @staticmethod def __magic_name__ ( *__lowercase : int , **__lowercase : Optional[Any] ) -> Optional[Any]: pass @is_pipeline_test @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @require_torch def __magic_name__ ( self : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) SCREAMING_SNAKE_CASE__ : List[str] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowercase ) , [ [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}], [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}], ] , ) SCREAMING_SNAKE_CASE__ : int =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @require_tf def __magic_name__ ( self : Union[str, Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[Any] =pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''' ) SCREAMING_SNAKE_CASE__ : Dict =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Tuple =image_classifier(__lowercase , candidate_labels=['''a''', '''b''', '''c'''] ) self.assertEqual( nested_simplify(__lowercase ) , [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], [ {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, {'''score''': 0.333, '''label''': ANY(__lowercase )}, ], ] , ) @slow @require_torch def __magic_name__ ( self : List[Any] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Any =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : List[str] =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def __magic_name__ ( self : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE__ : str =pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''' ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE__ : Optional[Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) SCREAMING_SNAKE_CASE__ : Any =image_classifier(__lowercase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowercase ) , [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE__ : List[Any] =image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowercase ) , [ [ {'''score''': 0.511, '''label''': '''remote'''}, {'''score''': 0.485, '''label''': '''cat'''}, {'''score''': 0.004, '''label''': '''plane'''}, ], ] * 5 , )
665
1