code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__) class __lowerCAmelCase ( UpperCamelCase__): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization _lowercase : str = field(default="""question-answering-extractive""" , metadata={"""include_in_asdict_even_if_is_default""": True}) _lowercase : ClassVar[Features] = Features({"""question""": Value("""string"""), """context""": Value("""string""")}) _lowercase : ClassVar[Features] = Features( { """answers""": Sequence( { """text""": Value("""string"""), """answer_start""": Value("""int32"""), }) }) _lowercase : str = "question" _lowercase : str = "context" _lowercase : str = "answers" @property def _lowercase ( self ) -> Dict[str, str]: '''simple docstring''' return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
95
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 ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = "arrow" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( split=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ , streaming=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : int =load_from_cache_file a__ : Tuple =file_format a__ : List[Any] =Spark( df=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , working_dir=lowerCAmelCase__ , **lowerCAmelCase__ , ) def _lowercase ( self ) -> str: '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) a__ : str =None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowerCAmelCase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
95
1
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase): _lowercase : Dict = AutoencoderKL _lowercase : Tuple = """sample""" _lowercase : Optional[int] = 1E-2 @property def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] =4 a__ : List[str] =3 a__ : Union[str, Any] =(3_2, 3_2) a__ : int =floats_tensor((batch_size, num_channels) + sizes ).to(lowerCAmelCase__ ) return {"sample": image} @property def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' return (3, 3_2, 3_2) @property def _lowercase ( self ) -> List[Any]: '''simple docstring''' return (3, 3_2, 3_2) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : List[Any] ={ "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, } a__ : List[str] =self.dummy_input return init_dict, inputs_dict def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' pass def _lowercase ( self ) -> List[Any]: '''simple docstring''' pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ , a__ : Union[str, Any] =self.prepare_init_args_and_inputs_for_common() a__ : Tuple =self.model_class(**lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) assert not model.is_gradient_checkpointing and model.training a__ : Optional[Any] =model(**lowerCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() a__ : str =torch.randn_like(lowerCAmelCase__ ) a__ : Tuple =(out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing a__ : Any =self.model_class(**lowerCAmelCase__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowerCAmelCase__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training a__ : Dict =model_a(**lowerCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() a__ : int =(out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) a__ : Union[str, Any] =dict(model.named_parameters() ) a__ : int =dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ , a__ : Optional[int] =AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowerCAmelCase__ ) a__ : Optional[Any] =model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Tuple =AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) a__ : str =model.to(lowerCAmelCase__ ) model.eval() if torch_device == "mps": a__ : Any =torch.manual_seed(0 ) else: a__ : Union[str, Any] =torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 ) a__ : Union[str, Any] =torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) a__ : Union[str, Any] =image.to(lowerCAmelCase__ ) with torch.no_grad(): a__ : Tuple =model(lowerCAmelCase__ , sample_posterior=lowerCAmelCase__ , generator=lowerCAmelCase__ ).sample a__ : Any =output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": a__ : str =torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": a__ : Dict =torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: a__ : Optional[int] =torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , rtol=1E-2 ) ) @slow class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' return F'''gaussian_noise_s={seed}_shape={"_".join([str(lowerCAmelCase__ ) for s in shape] )}.npy''' def _lowercase ( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self , lowerCAmelCase__=0 , lowerCAmelCase__=(4, 3, 5_1_2, 5_1_2) , lowerCAmelCase__=False ) -> Optional[Any]: '''simple docstring''' a__ : List[str] =torch.floataa if fpaa else torch.floataa a__ : Tuple =torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCAmelCase__ , lowerCAmelCase__ ) ) ).to(lowerCAmelCase__ ).to(lowerCAmelCase__ ) return image def _lowercase ( self , lowerCAmelCase__="CompVis/stable-diffusion-v1-4" , lowerCAmelCase__=False ) -> Any: '''simple docstring''' a__ : str ="fp16" if fpaa else None a__ : str =torch.floataa if fpaa else torch.floataa a__ : Dict =AutoencoderKL.from_pretrained( lowerCAmelCase__ , subfolder="vae" , torch_dtype=lowerCAmelCase__ , revision=lowerCAmelCase__ , ) model.to(lowerCAmelCase__ ).eval() return model def _lowercase ( self , lowerCAmelCase__=0 ) -> Optional[int]: '''simple docstring''' if torch_device == "mps": return torch.manual_seed(lowerCAmelCase__ ) return torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ ) @parameterized.expand( [ # fmt: off [3_3, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [4_7, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' a__ : List[Any] =self.get_sd_vae_model() a__ : Tuple =self.get_sd_image(lowerCAmelCase__ ) a__ : Tuple =self.get_generator(lowerCAmelCase__ ) with torch.no_grad(): a__ : Tuple =model(lowerCAmelCase__ , generator=lowerCAmelCase__ , sample_posterior=lowerCAmelCase__ ).sample assert sample.shape == image.shape a__ : Tuple =sample[-1, -2:, -2:, :2].flatten().float().cpu() a__ : Tuple =torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [4_7, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : Optional[int] =self.get_sd_vae_model(fpaa=lowerCAmelCase__ ) a__ : Any =self.get_sd_image(lowerCAmelCase__ , fpaa=lowerCAmelCase__ ) a__ : Dict =self.get_generator(lowerCAmelCase__ ) with torch.no_grad(): a__ : Union[str, Any] =model(lowerCAmelCase__ , generator=lowerCAmelCase__ , sample_posterior=lowerCAmelCase__ ).sample assert sample.shape == image.shape a__ : int =sample[-1, -2:, :2, -2:].flatten().float().cpu() a__ : List[str] =torch.tensor(lowerCAmelCase__ ) assert torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [4_7, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' a__ : Any =self.get_sd_vae_model() a__ : Optional[int] =self.get_sd_image(lowerCAmelCase__ ) with torch.no_grad(): a__ : Dict =model(lowerCAmelCase__ ).sample assert sample.shape == image.shape a__ : List[str] =sample[-1, -2:, -2:, :2].flatten().float().cpu() a__ : List[str] =torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [3_7, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' a__ : List[Any] =self.get_sd_vae_model() a__ : Optional[Any] =self.get_sd_image(lowerCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): a__ : Optional[Any] =model.decode(lowerCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] a__ : List[Any] =sample[-1, -2:, :2, -2:].flatten().cpu() a__ : Dict =torch.tensor(lowerCAmelCase__ ) assert torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [1_6, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : Optional[Any] =self.get_sd_vae_model(fpaa=lowerCAmelCase__ ) a__ : Tuple =self.get_sd_image(lowerCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=lowerCAmelCase__ ) with torch.no_grad(): a__ : Union[str, Any] =model.decode(lowerCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] a__ : Tuple =sample[-1, -2:, :2, -2:].flatten().float().cpu() a__ : Dict =torch.tensor(lowerCAmelCase__ ) assert torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def _lowercase ( self , lowerCAmelCase__ ) -> Dict: '''simple docstring''' a__ : int =self.get_sd_vae_model(fpaa=lowerCAmelCase__ ) a__ : List[Any] =self.get_sd_image(lowerCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=lowerCAmelCase__ ) with torch.no_grad(): a__ : Optional[int] =model.decode(lowerCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): a__ : Tuple =model.decode(lowerCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def _lowercase ( self , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' a__ : Dict =self.get_sd_vae_model() a__ : str =self.get_sd_image(lowerCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): a__ : List[str] =model.decode(lowerCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): a__ : Optional[int] =model.decode(lowerCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [4_7, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' a__ : Tuple =self.get_sd_vae_model() a__ : int =self.get_sd_image(lowerCAmelCase__ ) a__ : Any =self.get_generator(lowerCAmelCase__ ) with torch.no_grad(): a__ : str =model.encode(lowerCAmelCase__ ).latent_dist a__ : Union[str, Any] =dist.sample(generator=lowerCAmelCase__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] a__ : Optional[Any] =sample[0, -1, -3:, -3:].flatten().cpu() a__ : List[str] =torch.tensor(lowerCAmelCase__ ) a__ : Union[str, Any] =3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(lowerCAmelCase__ , lowerCAmelCase__ , atol=lowerCAmelCase__ )
95
from math import pi def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
95
1
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[int] = logging.get_logger(__name__) # TODO Update this UpperCAmelCase : Optional[Any] = { """facebook/esm-1b""": """https://huggingface.co/facebook/esm-1b/resolve/main/config.json""", # See all ESM models at https://huggingface.co/models?filter=esm } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[Any] = """esm""" def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=1_0_2_6 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__="absolute" , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=False , lowerCAmelCase__=False , lowerCAmelCase__=None , lowerCAmelCase__=None , **lowerCAmelCase__ , ) -> List[Any]: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , mask_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Union[str, Any] =vocab_size a__ : List[Any] =hidden_size a__ : Optional[Any] =num_hidden_layers a__ : str =num_attention_heads a__ : Tuple =intermediate_size a__ : List[Any] =hidden_dropout_prob a__ : Optional[int] =attention_probs_dropout_prob a__ : int =max_position_embeddings a__ : List[str] =initializer_range a__ : Optional[int] =layer_norm_eps a__ : Dict =position_embedding_type a__ : int =use_cache a__ : Tuple =emb_layer_norm_before a__ : Union[str, Any] =token_dropout a__ : List[Any] =is_folding_model if is_folding_model: if esmfold_config is None: logger.info("No esmfold_config supplied for folding model, using default values." ) a__ : List[Any] =EsmFoldConfig() elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any =EsmFoldConfig(**lowerCAmelCase__ ) a__ : Any =esmfold_config if vocab_list is None: logger.warning("No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!" ) a__ : List[Any] =get_default_vocab_list() else: a__ : List[str] =vocab_list else: a__ : Any =None a__ : str =None if self.esmfold_config is not None and getattr(self.esmfold_config , "use_esm_attn_map" , lowerCAmelCase__ ): raise ValueError("The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!" ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[Any] =super().to_dict() if isinstance(self.esmfold_config , lowerCAmelCase__ ): a__ : List[str] =self.esmfold_config.to_dict() return output @dataclass class __lowerCAmelCase : _lowercase : str = None _lowercase : bool = True _lowercase : bool = False _lowercase : bool = False _lowercase : bool = False _lowercase : float = 0 _lowercase : bool = True _lowercase : bool = False _lowercase : int = 128 _lowercase : "TrunkConfig" = None def _lowercase ( self ) -> List[Any]: '''simple docstring''' if self.trunk is None: a__ : List[Any] =TrunkConfig() elif isinstance(self.trunk , lowerCAmelCase__ ): a__ : Dict =TrunkConfig(**self.trunk ) def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Any =asdict(self ) a__ : List[str] =self.trunk.to_dict() return output @dataclass class __lowerCAmelCase : _lowercase : int = 48 _lowercase : int = 1024 _lowercase : int = 128 _lowercase : int = 32 _lowercase : int = 32 _lowercase : int = 32 _lowercase : float = 0 _lowercase : float = 0 _lowercase : bool = False _lowercase : int = 4 _lowercase : Optional[int] = 128 _lowercase : "StructureModuleConfig" = None def _lowercase ( self ) -> Any: '''simple docstring''' if self.structure_module is None: a__ : List[Any] =StructureModuleConfig() elif isinstance(self.structure_module , lowerCAmelCase__ ): a__ : Dict =StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(F'''`max_recycles` should be positive, got {self.max_recycles}.''' ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( "`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got" F''' {self.sequence_state_dim} and {self.sequence_state_dim}.''' ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( "`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got" F''' {self.pairwise_state_dim} and {self.pairwise_state_dim}.''' ) a__ : int =self.sequence_state_dim // self.sequence_head_width a__ : Dict =self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( "`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got" F''' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.''' ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( "`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got" F''' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.''' ) if self.pairwise_state_dim % 2 != 0: raise ValueError(F'''`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.''' ) if self.dropout >= 0.4: raise ValueError(F'''`dropout` should not be greater than 0.4, got {self.dropout}.''' ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =asdict(self ) a__ : List[str] =self.structure_module.to_dict() return output @dataclass class __lowerCAmelCase : _lowercase : int = 384 _lowercase : int = 128 _lowercase : int = 16 _lowercase : int = 128 _lowercase : int = 12 _lowercase : int = 4 _lowercase : int = 8 _lowercase : float = 0.1 _lowercase : int = 8 _lowercase : int = 1 _lowercase : int = 2 _lowercase : int = 7 _lowercase : int = 10 _lowercase : float = 1E-8 _lowercase : float = 1E5 def _lowercase ( self ) -> Tuple: '''simple docstring''' return asdict(self ) def _A ( ): """simple docstring""" return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
95
import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging UpperCAmelCase : int = { """cola""": 2, """mnli""": 3, """mrpc""": 2, """sst-2""": 2, """sts-b""": 1, """qqp""": 2, """qnli""": 2, """rte""": 2, """wnli""": 2, } logging.set_verbosity_info() def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any]=None ): """simple docstring""" a__ : Optional[int] =XLNetConfig.from_json_file(SCREAMING_SNAKE_CASE ) a__ : Dict =finetuning_task.lower() if finetuning_task is not None else "" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(f'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}''' ) a__ : List[str] =finetuning_task a__ : Tuple =GLUE_TASKS_NUM_LABELS[finetuning_task] a__ : List[Any] =XLNetForSequenceClassification(SCREAMING_SNAKE_CASE ) elif "squad" in finetuning_task: a__ : Optional[int] =finetuning_task a__ : Dict =XLNetForQuestionAnswering(SCREAMING_SNAKE_CASE ) else: a__ : List[Any] =XLNetLMHeadModel(SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Save pytorch-model a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print(f'''Save PyTorch model to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE ) print(f'''Save configuration file to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--xlnet_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained XLNet model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the folder to store the PyTorch model or dataset/vocab.""", ) parser.add_argument( """--finetuning_task""", default=None, type=str, help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""", ) UpperCAmelCase : int = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
95
1
from __future__ import annotations import os from typing import Any import requests UpperCAmelCase : str = """https://api.github.com""" # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user UpperCAmelCase : Optional[int] = BASE_URL + """/user""" # https://github.com/settings/tokens UpperCAmelCase : Optional[Any] = os.environ.get("""USER_TOKEN""", """""") def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" a__ : Tuple ={ "Authorization": f'''token {auth_token}''', "Accept": "application/vnd.github.v3+json", } return requests.get(SCREAMING_SNAKE_CASE , headers=SCREAMING_SNAKE_CASE ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(F"""{key}: {value}""") else: raise ValueError("""'USER_TOKEN' field cannot be empty.""")
95
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { """google/canine-s""": """https://huggingface.co/google/canine-s/resolve/main/config.json""", # See all CANINE models at https://huggingface.co/models?filter=canine } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[Any] = """canine""" def __init__( self , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_6 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=0 , lowerCAmelCase__=0XE0_00 , lowerCAmelCase__=0XE0_01 , lowerCAmelCase__=4 , lowerCAmelCase__=4 , lowerCAmelCase__=8 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_2_8 , **lowerCAmelCase__ , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Optional[int] =max_position_embeddings a__ : str =hidden_size a__ : Optional[Any] =num_hidden_layers a__ : Tuple =num_attention_heads a__ : Optional[Any] =intermediate_size a__ : Optional[int] =hidden_act a__ : List[Any] =hidden_dropout_prob a__ : Union[str, Any] =attention_probs_dropout_prob a__ : Optional[Any] =initializer_range a__ : Union[str, Any] =type_vocab_size a__ : Optional[int] =layer_norm_eps # Character config: a__ : int =downsampling_rate a__ : Optional[Any] =upsampling_kernel_size a__ : Union[str, Any] =num_hash_functions a__ : Any =num_hash_buckets a__ : int =local_transformer_stride
95
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow 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 DeformableDetrImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=[0.5, 0.5, 0.5] , lowerCAmelCase__=[0.5, 0.5, 0.5] , lowerCAmelCase__=True , lowerCAmelCase__=1 / 2_5_5 , lowerCAmelCase__=True , ) -> str: '''simple docstring''' a__ : str =size if size is not None else {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} a__ : Tuple =parent a__ : Any =batch_size a__ : int =num_channels a__ : List[str] =min_resolution a__ : Tuple =max_resolution a__ : Tuple =do_resize a__ : Dict =size a__ : List[str] =do_normalize a__ : Optional[Any] =image_mean a__ : Tuple =image_std a__ : Dict =do_rescale a__ : List[Any] =rescale_factor a__ : Optional[Any] =do_pad def _lowercase ( self ) -> Any: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=False ) -> Any: '''simple docstring''' if not batched: a__ : Tuple =image_inputs[0] if isinstance(lowerCAmelCase__ , Image.Image ): a__ , a__ : Union[str, Any] =image.size else: a__ , a__ : Optional[int] =image.shape[1], image.shape[2] if w < h: a__ : Optional[int] =int(self.size["shortest_edge"] * h / w ) a__ : List[Any] =self.size["shortest_edge"] elif w > h: a__ : Dict =self.size["shortest_edge"] a__ : List[Any] =int(self.size["shortest_edge"] * w / h ) else: a__ : List[Any] =self.size["shortest_edge"] a__ : int =self.size["shortest_edge"] else: a__ : List[Any] =[] for image in image_inputs: a__ , a__ : Optional[int] =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) a__ : Any =max(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : item[0] )[0] a__ : Union[str, Any] =max(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : Tuple = DeformableDetrImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : List[str] =DeformableDetrImageProcessingTester(self ) @property def _lowercase ( self ) -> Dict: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , "image_mean" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "image_std" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_rescale" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_pad" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) def _lowercase ( self ) -> str: '''simple docstring''' a__ : Optional[int] =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} ) self.assertEqual(image_processor.do_pad , lowerCAmelCase__ ) a__ : List[str] =self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=lowerCAmelCase__ ) self.assertEqual(image_processor.size , {"shortest_edge": 4_2, "longest_edge": 8_4} ) self.assertEqual(image_processor.do_pad , lowerCAmelCase__ ) def _lowercase ( self ) -> Dict: '''simple docstring''' pass def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : List[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : List[Any] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values a__ , a__ : List[Any] =self.image_processor_tester.get_expected_values(lowerCAmelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a__ , a__ : List[str] =self.image_processor_tester.get_expected_values(lowerCAmelCase__ , batched=lowerCAmelCase__ ) a__ : Optional[int] =image_processing(lowerCAmelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : List[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : int =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input a__ : Union[str, Any] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values a__ , a__ : Dict =self.image_processor_tester.get_expected_values(lowerCAmelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a__ : Union[str, Any] =image_processing(lowerCAmelCase__ , return_tensors="pt" ).pixel_values a__ , a__ : List[str] =self.image_processor_tester.get_expected_values(lowerCAmelCase__ , batched=lowerCAmelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _lowercase ( self ) -> int: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : Union[str, Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input a__ : int =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values a__ , a__ : List[Any] =self.image_processor_tester.get_expected_values(lowerCAmelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a__ : Union[str, Any] =image_processing(lowerCAmelCase__ , return_tensors="pt" ).pixel_values a__ , a__ : Tuple =self.image_processor_tester.get_expected_values(lowerCAmelCase__ , batched=lowerCAmelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : int =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: a__ : Optional[int] =json.loads(f.read() ) a__ : Any ={"image_id": 3_9_7_6_9, "annotations": target} # encode them a__ : Union[str, Any] =DeformableDetrImageProcessor() a__ : Tuple =image_processing(images=lowerCAmelCase__ , annotations=lowerCAmelCase__ , return_tensors="pt" ) # verify pixel values a__ : Tuple =torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , lowerCAmelCase__ ) a__ : Any =torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCAmelCase__ , atol=1E-4 ) ) # verify area a__ : List[Any] =torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCAmelCase__ ) ) # verify boxes a__ : Any =torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCAmelCase__ ) a__ : Optional[Any] =torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCAmelCase__ , atol=1E-3 ) ) # verify image_id a__ : int =torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCAmelCase__ ) ) # verify is_crowd a__ : str =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCAmelCase__ ) ) # verify class_labels a__ : List[str] =torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCAmelCase__ ) ) # verify orig_size a__ : Optional[int] =torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCAmelCase__ ) ) # verify size a__ : int =torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCAmelCase__ ) ) @slow def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : List[str] =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: a__ : int =json.loads(f.read() ) a__ : List[str] ={"file_name": "000000039769.png", "image_id": 3_9_7_6_9, "segments_info": target} a__ : List[Any] =pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them a__ : Any =DeformableDetrImageProcessor(format="coco_panoptic" ) a__ : Optional[Any] =image_processing(images=lowerCAmelCase__ , annotations=lowerCAmelCase__ , masks_path=lowerCAmelCase__ , return_tensors="pt" ) # verify pixel values a__ : Union[str, Any] =torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , lowerCAmelCase__ ) a__ : Union[str, Any] =torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCAmelCase__ , atol=1E-4 ) ) # verify area a__ : Dict =torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCAmelCase__ ) ) # verify boxes a__ : Optional[int] =torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCAmelCase__ ) a__ : Any =torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCAmelCase__ , atol=1E-3 ) ) # verify image_id a__ : int =torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCAmelCase__ ) ) # verify is_crowd a__ : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCAmelCase__ ) ) # verify class_labels a__ : Optional[Any] =torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCAmelCase__ ) ) # verify masks a__ : int =8_2_2_8_7_3 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCAmelCase__ ) # verify orig_size a__ : List[str] =torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCAmelCase__ ) ) # verify size a__ : int =torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCAmelCase__ ) )
95
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device UpperCAmelCase : int = False class __lowerCAmelCase ( unittest.TestCase): pass @nightly @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Optional[Any] =torch.manual_seed(0 ) a__ : Optional[Any] =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCAmelCase__ ) a__ : str =VersatileDiffusionPipeline.from_pretrained(lowerCAmelCase__ , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] =generator.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] ="cyberpunk 2077" a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Union[str, Any] =torch.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images a__ : int =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : str ="A painting of a squirrel eating a burger " a__ : Optional[int] =torch.manual_seed(0 ) a__ : str =pipe.text_to_image( prompt=lowerCAmelCase__ , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" ).images a__ : Any =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Optional[int] =np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : Optional[Any] =pipe.image_variation(lowerCAmelCase__ , generator=lowerCAmelCase__ , output_type="numpy" ).images a__ : Union[str, Any] =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
95
1
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def _A ( ): """simple docstring""" a__ : Union[str, Any] =[randint(-1_000 , 1_000 ) for i in range(10 )] a__ : Optional[Any] =randint(-5_000 , 5_000 ) return (arr, r) UpperCAmelCase : int = make_dataset() def _A ( SCREAMING_SNAKE_CASE : list[int] , SCREAMING_SNAKE_CASE : int ): """simple docstring""" for triplet in permutations(SCREAMING_SNAKE_CASE , 3 ): if sum(SCREAMING_SNAKE_CASE ) == target: return tuple(sorted(SCREAMING_SNAKE_CASE ) ) return (0, 0, 0) def _A ( SCREAMING_SNAKE_CASE : list[int] , SCREAMING_SNAKE_CASE : int ): """simple docstring""" arr.sort() a__ : int =len(SCREAMING_SNAKE_CASE ) for i in range(n - 1 ): a__ , a__ : Dict =i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def _A ( ): """simple docstring""" a__ : Any ="\nfrom __main__ import dataset, triplet_sum1, triplet_sum2\n" a__ : str ="\ntriplet_sum1(*dataset)\n" a__ : str ="\ntriplet_sum2(*dataset)\n" a__ : Optional[int] =repeat(setup=SCREAMING_SNAKE_CASE , stmt=SCREAMING_SNAKE_CASE , repeat=5 , number=10_000 ) a__ : List[Any] =repeat(setup=SCREAMING_SNAKE_CASE , stmt=SCREAMING_SNAKE_CASE , repeat=5 , number=10_000 ) return (min(SCREAMING_SNAKE_CASE ), min(SCREAMING_SNAKE_CASE )) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase : Union[str, Any] = solution_times() print(F"""The time for naive implementation is {times[0]}.""") print(F"""The time for optimized implementation is {times[1]}.""")
95
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class __lowerCAmelCase : def _lowercase ( self , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError() def _lowercase ( self ) -> int: '''simple docstring''' raise NotImplementedError() class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , **lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : str =tokenizer a__ : List[str] =skip_prompt a__ : List[Any] =decode_kwargs # variables used in the streaming process a__ : Dict =[] a__ : int =0 a__ : str =True def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError("TextStreamer only supports batch size 1" ) elif len(value.shape ) > 1: a__ : Any =value[0] if self.skip_prompt and self.next_tokens_are_prompt: a__ : Dict =False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith("\n" ): a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 # If the last token is a CJK character, we print the characters. elif len(lowerCAmelCase__ ) > 0 and self._is_chinese_char(ord(text[-1] ) ): a__ : List[str] =text[self.print_len :] self.print_len += len(lowerCAmelCase__ ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: a__ : str =text[self.print_len : text.rfind(" " ) + 1] self.print_len += len(lowerCAmelCase__ ) self.on_finalized_text(lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' if len(self.token_cache ) > 0: a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 else: a__ : Union[str, Any] ="" a__ : Any =True self.on_finalized_text(lowerCAmelCase__ , stream_end=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> Optional[Any]: '''simple docstring''' print(lowerCAmelCase__ , flush=lowerCAmelCase__ , end="" if not stream_end else None ) def _lowercase ( self , lowerCAmelCase__ ) -> str: '''simple docstring''' if ( (cp >= 0X4E_00 and cp <= 0X9F_FF) or (cp >= 0X34_00 and cp <= 0X4D_BF) # or (cp >= 0X2_00_00 and cp <= 0X2_A6_DF) # or (cp >= 0X2_A7_00 and cp <= 0X2_B7_3F) # or (cp >= 0X2_B7_40 and cp <= 0X2_B8_1F) # or (cp >= 0X2_B8_20 and cp <= 0X2_CE_AF) # or (cp >= 0XF9_00 and cp <= 0XFA_FF) or (cp >= 0X2_F8_00 and cp <= 0X2_FA_1F) # ): # return True return False class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , lowerCAmelCase__ = None , **lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' super().__init__(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : str =Queue() a__ : Optional[Any] =None a__ : Any =timeout def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> List[str]: '''simple docstring''' self.text_queue.put(lowerCAmelCase__ , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self ) -> Dict: '''simple docstring''' return self def _lowercase ( self ) -> int: '''simple docstring''' a__ : int =self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
95
1
import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __lowerCAmelCase ( UpperCamelCase__): @require_torch def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : List[Any] ="\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " a__ : Any ="\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " a__ : int ="\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache a__ : str ="hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(lowerCAmelCase__ ) BertModel.from_pretrained(lowerCAmelCase__ ) BertTokenizer.from_pretrained(lowerCAmelCase__ ) pipeline(task="fill-mask" , model=lowerCAmelCase__ ) # baseline - just load from_pretrained with normal network a__ : List[str] =[sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed a__ : List[str] =self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files a__ : Union[str, Any] ="1" a__ : List[str] =subprocess.run(lowerCAmelCase__ , env=lowerCAmelCase__ , check=lowerCAmelCase__ , capture_output=lowerCAmelCase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) @require_torch def _lowercase ( self ) -> int: '''simple docstring''' a__ : List[Any] ="\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " a__ : int ="\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " a__ : str ="\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache a__ : Any ="hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(lowerCAmelCase__ ) BertModel.from_pretrained(lowerCAmelCase__ ) BertTokenizer.from_pretrained(lowerCAmelCase__ ) pipeline(task="fill-mask" , model=lowerCAmelCase__ ) # baseline - just load from_pretrained with normal network a__ : str =[sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed a__ : Any =self.get_env() a__ : Dict =subprocess.run(lowerCAmelCase__ , env=lowerCAmelCase__ , check=lowerCAmelCase__ , capture_output=lowerCAmelCase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) @require_torch def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any ="\nfrom transformers import BertConfig, BertModel, BertTokenizer\n " a__ : Optional[Any] ="\nmname = \"hf-internal-testing/tiny-random-bert-sharded\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint(\"success\")\n " a__ : Optional[int] ="\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " # baseline - just load from_pretrained with normal network a__ : Any =[sys.executable, "-c", "\n".join([load, run] )] # should succeed a__ : List[Any] =self.get_env() a__ : Dict =subprocess.run(lowerCAmelCase__ , env=lowerCAmelCase__ , check=lowerCAmelCase__ , capture_output=lowerCAmelCase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) # next emulate no network a__ : Optional[int] =[sys.executable, "-c", "\n".join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files a__ : List[Any] ="1" a__ : str =subprocess.run(lowerCAmelCase__ , env=lowerCAmelCase__ , check=lowerCAmelCase__ , capture_output=lowerCAmelCase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) @require_torch def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any ="\nfrom transformers import pipeline\n " a__ : Any ="\nmname = \"hf-internal-testing/tiny-random-bert\"\npipe = pipeline(model=mname)\n " a__ : Tuple ="\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " a__ : Any =self.get_env() a__ : List[Any] ="1" a__ : Tuple =[sys.executable, "-c", "\n".join([load, mock, run] )] a__ : Any =subprocess.run(lowerCAmelCase__ , env=lowerCAmelCase__ , check=lowerCAmelCase__ , capture_output=lowerCAmelCase__ ) self.assertEqual(result.returncode , 1 , result.stderr ) self.assertIn( "You cannot infer task automatically within `pipeline` when using offline mode" , result.stderr.decode().replace("\n" , "" ) , ) @require_torch def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Dict ="\nfrom transformers import AutoModel\n " a__ : str ="\nmname = \"hf-internal-testing/test_dynamic_model\"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint(\"success\")\n " # baseline - just load from_pretrained with normal network a__ : List[str] =[sys.executable, "-c", "\n".join([load, run] )] # should succeed a__ : str =self.get_env() a__ : Optional[int] =subprocess.run(lowerCAmelCase__ , env=lowerCAmelCase__ , check=lowerCAmelCase__ , capture_output=lowerCAmelCase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files a__ : int ="1" a__ : List[str] =subprocess.run(lowerCAmelCase__ , env=lowerCAmelCase__ , check=lowerCAmelCase__ , capture_output=lowerCAmelCase__ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() )
95
def _A ( SCREAMING_SNAKE_CASE : int = 50 ): """simple docstring""" a__ : Any =[1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
95
1
import warnings from ..trainer import Trainer from ..utils import logging UpperCAmelCase : Optional[int] = logging.get_logger(__name__) class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__=None , **lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , lowerCAmelCase__ , ) super().__init__(args=lowerCAmelCase__ , **lowerCAmelCase__ )
95
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if len(SCREAMING_SNAKE_CASE ) == 0: return [] a__ , a__ : int =min(SCREAMING_SNAKE_CASE ), max(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =int(max_value - min_value ) + 1 a__ : list[list] =[[] for _ in range(SCREAMING_SNAKE_CASE )] for i in my_list: buckets[int(i - min_value )].append(SCREAMING_SNAKE_CASE ) return [v for bucket in buckets for v in sorted(SCREAMING_SNAKE_CASE )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
95
1
import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class __lowerCAmelCase : @property def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' return self.get_dummy_input() @property def _lowercase ( self ) -> Any: '''simple docstring''' if self.block_type == "down": return (4, 3_2, 1_6, 1_6) elif self.block_type == "mid": return (4, 3_2, 3_2, 3_2) elif self.block_type == "up": return (4, 3_2, 6_4, 6_4) raise ValueError(F'''\'{self.block_type}\' is not a supported block_type. Set it to \'up\', \'mid\', or \'down\'.''' ) def _lowercase ( self , lowerCAmelCase__=True , lowerCAmelCase__=False , lowerCAmelCase__=False , lowerCAmelCase__=False , ) -> List[str]: '''simple docstring''' a__ : List[str] =4 a__ : str =3_2 a__ : Dict =(3_2, 3_2) a__ : Optional[int] =torch.manual_seed(0 ) a__ : List[Any] =torch.device(lowerCAmelCase__ ) a__ : Union[str, Any] =(batch_size, num_channels) + sizes a__ : Dict =randn_tensor(lowerCAmelCase__ , generator=lowerCAmelCase__ , device=lowerCAmelCase__ ) a__ : Optional[int] ={"hidden_states": hidden_states} if include_temb: a__ : List[Any] =1_2_8 a__ : List[str] =randn_tensor((batch_size, temb_channels) , generator=lowerCAmelCase__ , device=lowerCAmelCase__ ) if include_res_hidden_states_tuple: a__ : Optional[int] =torch.manual_seed(1 ) a__ : Tuple =(randn_tensor(lowerCAmelCase__ , generator=lowerCAmelCase__ , device=lowerCAmelCase__ ),) if include_encoder_hidden_states: a__ : Dict =floats_tensor((batch_size, 3_2, 3_2) ).to(lowerCAmelCase__ ) if include_skip_sample: a__ : Dict =randn_tensor(((batch_size, 3) + sizes) , generator=lowerCAmelCase__ , device=lowerCAmelCase__ ) return dummy_input def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Optional[int] ={ "in_channels": 3_2, "out_channels": 3_2, "temb_channels": 1_2_8, } if self.block_type == "up": a__ : Any =3_2 if self.block_type == "mid": init_dict.pop("out_channels" ) a__ : Optional[int] =self.dummy_input return init_dict, inputs_dict def _lowercase ( self , lowerCAmelCase__ ) -> str: '''simple docstring''' a__ , a__ : Union[str, Any] =self.prepare_init_args_and_inputs_for_common() a__ : Dict =self.block_class(**lowerCAmelCase__ ) unet_block.to(lowerCAmelCase__ ) unet_block.eval() with torch.no_grad(): a__ : List[Any] =unet_block(**lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : str =output[0] self.assertEqual(output.shape , self.output_shape ) a__ : int =output[0, -1, -3:, -3:] a__ : Any =torch.tensor(lowerCAmelCase__ ).to(lowerCAmelCase__ ) assert torch_all_close(output_slice.flatten() , lowerCAmelCase__ , atol=5E-3 ) @unittest.skipIf(torch_device == "mps" , "Training is not supported in mps" ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ , a__ : Dict =self.prepare_init_args_and_inputs_for_common() a__ : Any =self.block_class(**lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.train() a__ : int =model(**lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : List[str] =output[0] a__ : List[Any] =torch.device(lowerCAmelCase__ ) a__ : List[str] =randn_tensor(output.shape , device=lowerCAmelCase__ ) a__ : List[Any] =torch.nn.functional.mse_loss(lowerCAmelCase__ , lowerCAmelCase__ ) loss.backward()
95
import numpy as np def _A ( SCREAMING_SNAKE_CASE : np.array ): """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
95
1
from __future__ import annotations import math def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True UpperCAmelCase : Dict = [num for num in range(3, 100001, 2) if not is_prime(num)] def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("n must be an integer" ) if n <= 0: raise ValueError("n must be >= 0" ) a__ : List[Any] =[] for num in range(len(SCREAMING_SNAKE_CASE ) ): a__ : int =0 while 2 * i * i <= odd_composites[num]: a__ : Optional[Any] =odd_composites[num] - 2 * i * i if is_prime(SCREAMING_SNAKE_CASE ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(SCREAMING_SNAKE_CASE ) == n: return list_nums return [] def _A ( ): """simple docstring""" return compute_nums(1 )[0] if __name__ == "__main__": print(F"""{solution() = }""")
95
import numpy # List of input, output pairs UpperCAmelCase : str = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) UpperCAmelCase : Optional[int] = (((515, 22, 13), 555), ((61, 35, 49), 150)) UpperCAmelCase : str = [2, 4, 1, 5] UpperCAmelCase : List[str] = len(train_data) UpperCAmelCase : Dict = 0.0_0_9 def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Tuple="train" ): """simple docstring""" return calculate_hypothesis_value(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) - output( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : Tuple =0 for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : int=m ): """simple docstring""" a__ : Any =0 for i in range(SCREAMING_SNAKE_CASE ): if index == -1: summation_value += _error(SCREAMING_SNAKE_CASE ) else: summation_value += _error(SCREAMING_SNAKE_CASE ) * train_data[i][0][index] return summation_value def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Any =summation_of_cost_derivative(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) / m return cost_derivative_value def _A ( ): """simple docstring""" global parameter_vector # Tune these values to set a tolerance value for predicted output a__ : Dict =0.0_0_0_0_0_2 a__ : Union[str, Any] =0 a__ : Any =0 while True: j += 1 a__ : Any =[0, 0, 0, 0] for i in range(0 , len(SCREAMING_SNAKE_CASE ) ): a__ : Tuple =get_cost_derivative(i - 1 ) a__ : List[Any] =( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE , rtol=SCREAMING_SNAKE_CASE , ): break a__ : Optional[Any] =temp_parameter_vector print(("Number of iterations:", j) ) def _A ( ): """simple docstring""" for i in range(len(SCREAMING_SNAKE_CASE ) ): print(("Actual output value:", output(SCREAMING_SNAKE_CASE , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(SCREAMING_SNAKE_CASE , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("""\nTesting gradient descent for a linear hypothesis function.\n""") test_gradient_descent()
95
1
def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if any(not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or x < 0 for x in sequence ): raise TypeError("Sequence must be list of non-negative integers" ) for _ in range(len(SCREAMING_SNAKE_CASE ) ): for i, (rod_upper, rod_lower) in enumerate(zip(SCREAMING_SNAKE_CASE , sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
95
def _A ( SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" a__ : Optional[Any] =len(SCREAMING_SNAKE_CASE ) while cur > 1: # Find the maximum number in arr a__ : List[Any] =arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi a__ : int =arr[mi::-1] + arr[mi + 1 : len(SCREAMING_SNAKE_CASE )] # Reverse whole list a__ : List[str] =arr[cur - 1 :: -1] + arr[cur : len(SCREAMING_SNAKE_CASE )] cur -= 1 return arr if __name__ == "__main__": UpperCAmelCase : int = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase : Optional[int] = [int(item) for item in user_input.split(""",""")] print(pancake_sort(unsorted))
95
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """adapter_layer""": """encoder.layers.*.adapter_layer""", """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""", """pooling_layer.linear""": """projector""", """pooling_layer.projection""": """classifier""", } UpperCAmelCase : str = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """projector""", """classifier""", ] def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" a__ : Dict ={} with open(SCREAMING_SNAKE_CASE , "r" ) as file: for line_number, line in enumerate(SCREAMING_SNAKE_CASE ): a__ : Union[str, Any] =line.strip() if line: a__ : Union[str, Any] =line.split() a__ : Any =line_number a__ : Any =words[0] a__ : Optional[int] =value return result def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" for attribute in key.split("." ): a__ : Union[str, Any] =getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : List[str] =None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(SCREAMING_SNAKE_CASE ): a__ : Tuple =PARAM_MAPPING[full_name.split("." )[-1]] a__ : Any ="param" if weight_type is not None and weight_type != "param": a__ : int =getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).shape elif weight_type is not None and weight_type == "param": a__ : int =hf_pointer for attribute in hf_param_name.split("." ): a__ : Union[str, Any] =getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Union[str, Any] =shape_pointer.shape # let's reduce dimension a__ : Optional[int] =value[0] else: a__ : Union[str, Any] =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__ : List[str] =value elif weight_type == "weight_g": a__ : List[Any] =value elif weight_type == "weight_v": a__ : Any =value elif weight_type == "bias": a__ : Optional[int] =value elif weight_type == "param": for attribute in hf_param_name.split("." ): a__ : str =getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : str =value else: a__ : str =value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" a__ : List[str] =None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(SCREAMING_SNAKE_CASE ): a__ : List[Any] =PARAM_MAPPING[full_name.split("." )[-1]] a__ : List[Any] ="param" if weight_type is not None and weight_type != "param": a__ : Union[str, Any] =".".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": a__ : Union[str, Any] =".".join([key, hf_param_name] ) else: a__ : Dict =key a__ : Dict =value if "lm_head" in full_key else value[0] UpperCAmelCase : int = { """W_a""": """linear_1.weight""", """W_b""": """linear_2.weight""", """b_a""": """linear_1.bias""", """b_b""": """linear_2.bias""", """ln_W""": """norm.weight""", """ln_b""": """norm.bias""", } def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Optional[int]=None , SCREAMING_SNAKE_CASE : Optional[int]=None ): """simple docstring""" a__ : Optional[int] =False for key, mapped_key in MAPPING.items(): a__ : Union[str, Any] ="wav2vec2." + 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__ : List[str] =True if "*" in mapped_key: a__ : Any =name.split(SCREAMING_SNAKE_CASE )[0].split("." )[-2] a__ : Tuple =mapped_key.replace("*" , SCREAMING_SNAKE_CASE ) if "weight_g" in name: a__ : int ="weight_g" elif "weight_v" in name: a__ : int ="weight_v" elif "bias" in name: a__ : List[Any] ="bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj a__ : int ="weight" else: a__ : Tuple =None if hf_dict is not None: rename_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: set_recursively(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return is_used return is_used def _A ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" a__ : List[Any] =[] a__ : Tuple =fairseq_model.state_dict() a__ : Any =hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): a__ : List[str] =False if "conv_layers" in name: load_conv_layer( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == "group" , ) a__ : List[str] =True else: a__ : Optional[Any] =load_wavaveca_layer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _A ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" a__ : Tuple =full_name.split("conv_layers." )[-1] a__ : Tuple =name.split("." ) a__ : str =int(items[0] ) a__ : Tuple =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__ : str =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__ : List[Any] =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__ : int =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__ : Any =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(SCREAMING_SNAKE_CASE ) @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int]=None , SCREAMING_SNAKE_CASE : Optional[Any]=None , SCREAMING_SNAKE_CASE : List[Any]=True , SCREAMING_SNAKE_CASE : int=False ): """simple docstring""" if config_path is not None: a__ : Union[str, Any] =WavaVecaConfig.from_pretrained(SCREAMING_SNAKE_CASE ) else: a__ : str =WavaVecaConfig() if is_seq_class: a__ : Optional[int] =read_txt_into_dict(SCREAMING_SNAKE_CASE ) a__ : List[str] =idalabel a__ : List[Any] =WavaVecaForSequenceClassification(SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE ) elif is_finetuned: if dict_path: a__ : Tuple =Dictionary.load(SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq a__ : str =target_dict.pad_index a__ : Dict =target_dict.bos_index a__ : int =target_dict.eos_index a__ : str =len(target_dict.symbols ) a__ : Optional[Any] =os.path.join(SCREAMING_SNAKE_CASE , "vocab.json" ) if not os.path.isdir(SCREAMING_SNAKE_CASE ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(SCREAMING_SNAKE_CASE ) ) return os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) a__ : Dict =target_dict.indices # fairseq has the <pad> and <s> switched a__ : Optional[Any] =0 a__ : Any =1 with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as vocab_handle: json.dump(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Optional[int] =WavaVecaCTCTokenizer( SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="|" , do_lower_case=SCREAMING_SNAKE_CASE , ) a__ : List[Any] =True if config.feat_extract_norm == "layer" else False a__ : Optional[int] =WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , ) a__ : int =WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =WavaVecaForCTC(SCREAMING_SNAKE_CASE ) else: a__ : int =WavaVecaForPreTraining(SCREAMING_SNAKE_CASE ) if is_finetuned or is_seq_class: a__ , a__ , a__ : Dict =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) else: a__ : str =argparse.Namespace(task="audio_pretraining" ) a__ : Tuple =fairseq.tasks.setup_task(SCREAMING_SNAKE_CASE ) a__ , a__ , a__ : Dict =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=SCREAMING_SNAKE_CASE ) a__ : Optional[int] =model[0].eval() recursively_load_weights(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , not is_finetuned ) hf_wavavec.save_pretrained(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCAmelCase : Any = 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""" ) parser.add_argument( """--is_seq_class""", action="""store_true""", help="""Whether the model to convert is a fine-tuned sequence classification model or not""", ) UpperCAmelCase : Union[str, Any] = parser.parse_args() UpperCAmelCase : Optional[Any] = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
95
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Any =tempfile.mkdtemp() # fmt: off a__ : List[Any] =["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on a__ : str =dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) a__ : List[Any] =["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""] a__ : Optional[int] ={"unk_token": "<unk>"} a__ : Optional[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) a__ : Tuple =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowerCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(lowerCAmelCase__ ) ) a__ : Optional[Any] ={ "do_resize": True, "size": 2_0, "do_center_crop": True, "crop_size": 1_8, "do_normalize": True, "image_mean": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], "image_std": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } a__ : Dict =os.path.join(self.tmpdirname , lowerCAmelCase__ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Any: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =[np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] a__ : List[Any] =[Image.fromarray(np.moveaxis(lowerCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Union[str, Any] =self.get_tokenizer() a__ : int =self.get_rust_tokenizer() a__ : List[str] =self.get_image_processor() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) a__ : Optional[Any] =CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=lowerCAmelCase__ ) a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) a__ : Dict =CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor , lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a__ : str =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) a__ : int =self.get_image_processor(do_normalize=lowerCAmelCase__ , padding_value=1.0 ) a__ : Optional[Any] =CLIPSegProcessor.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 _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : str =self.get_image_processor() a__ : Optional[int] =self.get_tokenizer() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : str =self.prepare_image_inputs() a__ : Any =image_processor(lowerCAmelCase__ , return_tensors="np" ) a__ : Optional[int] =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 _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : List[Any] =self.get_tokenizer() a__ : Optional[int] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Union[str, Any] ="lower newer" a__ : List[str] =processor(text=lowerCAmelCase__ ) a__ : str =tokenizer(lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =self.get_image_processor() a__ : Dict =self.get_tokenizer() a__ : Union[str, Any] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict ="lower newer" a__ : int =self.prepare_image_inputs() a__ : Any =processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> str: '''simple docstring''' a__ : Union[str, Any] =self.get_image_processor() a__ : Optional[Any] =self.get_tokenizer() a__ : str =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : int =self.prepare_image_inputs() a__ : Union[str, Any] =self.prepare_image_inputs() a__ : Tuple =processor(images=lowerCAmelCase__ , visual_prompt=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "conditional_pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : Any =self.get_tokenizer() a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a__ : Optional[Any] =processor.batch_decode(lowerCAmelCase__ ) a__ : Dict =tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
95
1
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 __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[int] =inspect.getfile(accelerate.test_utils ) a__ : List[Any] =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 a__ : List[str] =test_metrics @require_cpu def _lowercase ( self ) -> Optional[int]: '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def _lowercase ( self ) -> Dict: '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def _lowercase ( self ) -> List[str]: '''simple docstring''' self.test_metrics.main() @require_multi_gpu def _lowercase ( self ) -> str: '''simple docstring''' print(F'''Found {torch.cuda.device_count()} devices.''' ) a__ : List[str] =["torchrun", F'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowerCAmelCase__ , env=os.environ.copy() )
95
def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) if len(SCREAMING_SNAKE_CASE ) == 1: return True a__ : Union[str, Any] =series[1] - series[0] for index in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) a__ : Any =0 for val in series: answer += val return answer / len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
95
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) UpperCAmelCase : Tuple = { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json""" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : int = """speech_to_text_2""" _lowercase : Tuple = ["""past_key_values"""] _lowercase : Union[str, Any] = {"""num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCAmelCase__=1_0_0_0_0 , lowerCAmelCase__=6 , lowerCAmelCase__=2_0_4_8 , lowerCAmelCase__=4 , lowerCAmelCase__=0.0 , lowerCAmelCase__=True , lowerCAmelCase__="relu" , lowerCAmelCase__=2_5_6 , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.02 , lowerCAmelCase__=2 , lowerCAmelCase__=True , lowerCAmelCase__=1 , lowerCAmelCase__=0 , lowerCAmelCase__=2 , lowerCAmelCase__=1_0_2_4 , **lowerCAmelCase__ , ) -> Union[str, Any]: '''simple docstring''' a__ : List[str] =vocab_size a__ : List[str] =d_model a__ : List[str] =decoder_ffn_dim a__ : Union[str, Any] =decoder_layers a__ : Dict =decoder_attention_heads a__ : Union[str, Any] =dropout a__ : str =attention_dropout a__ : Tuple =activation_dropout a__ : List[str] =activation_function a__ : Dict =init_std a__ : str =decoder_layerdrop a__ : Dict =use_cache a__ : List[str] =decoder_layers a__ : List[Any] =scale_embedding # scale factor will be sqrt(d_model) if True a__ : Dict =max_target_positions super().__init__( pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , **lowerCAmelCase__ , )
95
import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Tuple = """M-CLIP""" def __init__( self , lowerCAmelCase__=1_0_2_4 , lowerCAmelCase__=7_6_8 , **lowerCAmelCase__ ) -> Any: '''simple docstring''' a__ : int =transformerDimSize a__ : Dict =imageDimSize super().__init__(**lowerCAmelCase__ ) class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = MCLIPConfig def __init__( self , lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> List[str]: '''simple docstring''' super().__init__(lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Tuple =XLMRobertaModel(lowerCAmelCase__ ) a__ : List[str] =torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[Any] =self.transformer(input_ids=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ )[0] a__ : int =(embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(lowerCAmelCase__ ), embs
95
1
import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging UpperCAmelCase : Tuple = logging.get_logger(__name__) class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = CLIPConfig _lowercase : List[Any] = ["""CLIPEncoderLayer"""] def __init__( self , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' super().__init__(lowerCAmelCase__ ) a__ : List[str] =CLIPVisionModelWithProjection(config.vision_config ) a__ : List[str] =nn.Linear(config.vision_config.projection_dim , 1 ) a__ : Optional[Any] =nn.Linear(config.vision_config.projection_dim , 1 ) @torch.no_grad() def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=0.5 , lowerCAmelCase__=0.5 ) -> List[str]: '''simple docstring''' a__ : str =self.vision_model(lowerCAmelCase__ )[0] a__ : Union[str, Any] =self.p_head(lowerCAmelCase__ ) a__ : Optional[Any] =nsfw_detected.flatten() a__ : Any =nsfw_detected > p_threshold a__ : List[Any] =nsfw_detected.tolist() if any(lowerCAmelCase__ ): logger.warning( "Potential NSFW content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, nsfw_detected_ in enumerate(lowerCAmelCase__ ): if nsfw_detected_: a__ : List[str] =np.zeros(images[idx].shape ) a__ : List[Any] =self.w_head(lowerCAmelCase__ ) a__ : List[str] =watermark_detected.flatten() a__ : Dict =watermark_detected > w_threshold a__ : Optional[int] =watermark_detected.tolist() if any(lowerCAmelCase__ ): logger.warning( "Potential watermarked content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, watermark_detected_ in enumerate(lowerCAmelCase__ ): if watermark_detected_: a__ : Union[str, Any] =np.zeros(images[idx].shape ) return images, nsfw_detected, watermark_detected
95
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 ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to properly calculate the metrics on the # validation dataset when in a distributed system, and builds off the # `nlp_example.py` script. # # 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 help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # 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 : Any = 16 UpperCAmelCase : str = 32 def _A ( SCREAMING_SNAKE_CASE : Accelerator , SCREAMING_SNAKE_CASE : int = 16 ): """simple docstring""" a__ : int =AutoTokenizer.from_pretrained("bert-base-cased" ) a__ : List[str] =load_dataset("glue" , "mrpc" ) def tokenize_function(SCREAMING_SNAKE_CASE : List[Any] ): # max_length=None => use the model max length (it's actually the default) a__ : int =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__ : Dict =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__ : Dict =tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(SCREAMING_SNAKE_CASE : str ): # On TPU it's best to pad everything to the same length or training will be very slow. a__ : Optional[Any] =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__ : str =16 elif accelerator.mixed_precision != "no": a__ : Union[str, Any] =8 else: a__ : List[str] =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__ : Any =DataLoader( tokenized_datasets["train"] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE ) a__ : int =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 : str = mocked_dataloaders # noqa: F811 def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : str ): """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , SCREAMING_SNAKE_CASE ) == "1": a__ : Tuple =2 # Initialize accelerator a__ : int =Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a__ : Optional[int] =config["lr"] a__ : Union[str, Any] =int(config["num_epochs"] ) a__ : Any =int(config["seed"] ) a__ : Dict =int(config["batch_size"] ) a__ : int =evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation a__ : int =1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: a__ : Dict =batch_size // MAX_GPU_BATCH_SIZE a__ : Tuple =MAX_GPU_BATCH_SIZE set_seed(SCREAMING_SNAKE_CASE ) a__ , a__ : Optional[int] =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__ : List[str] =model.to(accelerator.device ) # Instantiate optimizer a__ : List[Any] =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) // gradient_accumulation_steps , ) # 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__ : Optional[int] =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() 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 ) a__ : Dict =model(**SCREAMING_SNAKE_CASE ) a__ : List[Any] =outputs.loss a__ : List[str] =loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() a__ : Optional[Any] =0 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__ : Any =model(**SCREAMING_SNAKE_CASE ) a__ : str =outputs.logits.argmax(dim=-1 ) a__ , a__ : List[str] =accelerator.gather((predictions, batch["labels"]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(SCREAMING_SNAKE_CASE ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples a__ : Optional[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] a__ : Dict =references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=SCREAMING_SNAKE_CASE , references=SCREAMING_SNAKE_CASE , ) a__ : Tuple =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , SCREAMING_SNAKE_CASE ) def _A ( ): """simple docstring""" a__ : List[str] =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." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) a__ : str =parser.parse_args() a__ : Optional[int] ={"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
95
1
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( "files" , [ ["full:README.md", "dataset_infos.json"], ["empty:README.md", "dataset_infos.json"], ["dataset_infos.json"], ["full:README.md"], ] , ) def _A ( SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" a__ : Optional[Any] =tmp_path_factory.mktemp("dset_infos_dir" ) if "full:README.md" in files: with open(dataset_infos_dir / "README.md" , "w" ) as f: f.write("---\ndataset_info:\n dataset_size: 42\n---" ) if "empty:README.md" in files: with open(dataset_infos_dir / "README.md" , "w" ) as f: f.write("" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / "dataset_infos.json" , "w" ) as f: f.write("{\"default\": {\"dataset_size\": 42}}" ) a__ : str =DatasetInfosDict.from_directory(SCREAMING_SNAKE_CASE ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( "dataset_info" , [ DatasetInfo(), DatasetInfo( description="foo" , features=Features({"a": Value("int32" )} ) , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train"}] , download_size=42 , ), ] , ) def _A ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : DatasetInfo ): """simple docstring""" a__ : List[str] =str(SCREAMING_SNAKE_CASE ) dataset_info.write_to_directory(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =DatasetInfo.from_directory(SCREAMING_SNAKE_CASE ) assert dataset_info == reloaded assert os.path.exists(os.path.join(SCREAMING_SNAKE_CASE , "dataset_info.json" ) ) def _A ( ): """simple docstring""" a__ : Tuple =DatasetInfo( description="foo" , citation="bar" , homepage="https://foo.bar" , license="CC0" , features=Features({"a": Value("int32" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train", "num_examples": 42}] , download_checksums={} , download_size=1_337 , post_processing_size=442 , dataset_size=1_234 , size_in_bytes=1_337 + 442 + 1_234 , ) a__ : Union[str, Any] =dataset_info._to_yaml_dict() assert sorted(SCREAMING_SNAKE_CASE ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) a__ : Union[str, Any] =yaml.safe_dump(SCREAMING_SNAKE_CASE ) a__ : Any =yaml.safe_load(SCREAMING_SNAKE_CASE ) assert dataset_info_yaml_dict == reloaded def _A ( ): """simple docstring""" a__ : Dict =DatasetInfo() a__ : Tuple =dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( "dataset_infos_dict" , [ DatasetInfosDict(), DatasetInfosDict({"default": DatasetInfo()} ), DatasetInfosDict({"my_config_name": DatasetInfo()} ), DatasetInfosDict( { "default": DatasetInfo( description="foo" , features=Features({"a": Value("int32" )} ) , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train"}] , download_size=42 , ) } ), DatasetInfosDict( { "v1": DatasetInfo(dataset_size=42 ), "v2": DatasetInfo(dataset_size=1_337 ), } ), ] , ) def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : DatasetInfosDict ): """simple docstring""" a__ : str =str(SCREAMING_SNAKE_CASE ) dataset_infos_dict.write_to_directory(SCREAMING_SNAKE_CASE ) a__ : Tuple =DatasetInfosDict.from_directory(SCREAMING_SNAKE_CASE ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): a__ : Optional[int] =config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml a__ : Optional[int] =DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(SCREAMING_SNAKE_CASE , "README.md" ) )
95
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 MobileViTImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] =size if size is not None else {"shortest_edge": 2_0} a__ : List[str] =crop_size if crop_size is not None else {"height": 1_8, "width": 1_8} a__ : Tuple =parent a__ : Union[str, Any] =batch_size a__ : List[str] =num_channels a__ : List[Any] =image_size a__ : str =min_resolution a__ : Optional[int] =max_resolution a__ : Tuple =do_resize a__ : Union[str, Any] =size a__ : List[Any] =do_center_crop a__ : List[str] =crop_size a__ : Optional[int] =do_flip_channel_order def _lowercase ( self ) -> Optional[int]: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : int = MobileViTImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : Tuple =MobileViTImageProcessingTester(self ) @property def _lowercase ( self ) -> List[str]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : str =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_flip_channel_order" ) ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : List[Any] =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 2_0} ) self.assertEqual(image_processor.crop_size , {"height": 1_8, "width": 1_8} ) a__ : Union[str, Any] =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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' pass def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : 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 a__ : List[Any] =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : List[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input a__ : 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 a__ : int =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : int =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input a__ : List[str] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a__ : List[str] =image_processing(lowerCAmelCase__ , 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"], ) , )
95
1
import inspect import unittest from transformers import MobileNetVaConfig 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 transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __lowerCAmelCase ( UpperCamelCase__): def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : Optional[int] =self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCAmelCase__ , "tf_padding" ) ) self.parent.assertTrue(hasattr(lowerCAmelCase__ , "depth_multiplier" ) ) class __lowerCAmelCase : def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=1_3 , lowerCAmelCase__=3 , lowerCAmelCase__=3_2 , lowerCAmelCase__=0.25 , lowerCAmelCase__=8 , lowerCAmelCase__=True , lowerCAmelCase__=1_0_2_4 , lowerCAmelCase__=3_2 , lowerCAmelCase__="relu6" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.02 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=1_0 , lowerCAmelCase__=None , ) -> Optional[int]: '''simple docstring''' a__ : Optional[int] =parent a__ : Any =batch_size a__ : Tuple =num_channels a__ : Dict =image_size a__ : Any =depth_multiplier a__ : Tuple =min_depth a__ : Dict =tf_padding a__ : Dict =int(last_hidden_size * depth_multiplier ) a__ : Optional[int] =output_stride a__ : Union[str, Any] =hidden_act a__ : List[Any] =classifier_dropout_prob a__ : Optional[int] =use_labels a__ : Optional[Any] =is_training a__ : int =num_labels a__ : Optional[int] =initializer_range a__ : int =scope def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Union[str, Any] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a__ : List[Any] =None a__ : str =None if self.use_labels: a__ : Dict =ids_tensor([self.batch_size] , self.num_labels ) a__ : Optional[int] =ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) a__ : Union[str, Any] =self.get_config() return config, pixel_values, labels, pixel_labels def _lowercase ( self ) -> Tuple: '''simple docstring''' return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> str: '''simple docstring''' a__ : Optional[int] =MobileNetVaModel(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : int =model(lowerCAmelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' a__ : Tuple =self.num_labels a__ : Optional[int] =MobileNetVaForImageClassification(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : Optional[int] =model(lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self ) -> int: '''simple docstring''' a__ : str =self.prepare_config_and_inputs() a__ , a__ , a__ , a__ : List[Any] =config_and_inputs a__ : int ={"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase): _lowercase : Any = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () _lowercase : str = ( {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification} if is_torch_available() else {} ) _lowercase : Tuple = False _lowercase : int = False _lowercase : Tuple = False _lowercase : List[str] = False def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =MobileNetVaModelTester(self ) a__ : Optional[Any] =MobileNetVaConfigTester(self , config_class=lowerCAmelCase__ , has_text_modality=lowerCAmelCase__ ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" ) def _lowercase ( self ) -> List[str]: '''simple docstring''' pass @unittest.skip(reason="MobileNetV1 does not output attentions" ) def _lowercase ( self ) -> str: '''simple docstring''' pass def _lowercase ( self ) -> Any: '''simple docstring''' a__ , a__ : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : str =model_class(lowerCAmelCase__ ) a__ : Optional[int] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : List[Any] =[*signature.parameters.keys()] a__ : List[Any] =["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCAmelCase__ ) def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase__ ) def _lowercase ( self ) -> str: '''simple docstring''' def check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): a__ : str =model_class(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() with torch.no_grad(): a__ : int =model(**self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ ) ) a__ : Optional[int] =outputs.hidden_states a__ : Optional[Any] =2_6 self.assertEqual(len(lowerCAmelCase__ ) , lowerCAmelCase__ ) a__ , a__ : Dict =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Dict =True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a__ : List[str] =True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self ) -> int: '''simple docstring''' a__ : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__ ) @slow def _lowercase ( self ) -> List[str]: '''simple docstring''' for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : List[Any] =MobileNetVaModel.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) def _A ( ): """simple docstring""" a__ : Dict =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase): @cached_property def _lowercase ( self ) -> Optional[int]: '''simple docstring''' return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None ) @slow def _lowercase ( self ) -> int: '''simple docstring''' a__ : Union[str, Any] =MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(lowerCAmelCase__ ) a__ : List[str] =self.default_image_processor a__ : int =prepare_img() a__ : Optional[Any] =image_processor(images=lowerCAmelCase__ , return_tensors="pt" ).to(lowerCAmelCase__ ) # forward pass with torch.no_grad(): a__ : str =model(**lowerCAmelCase__ ) # verify the logits a__ : Any =torch.Size((1, 1_0_0_1) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase__ ) a__ : int =torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(lowerCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase__ , atol=1E-4 ) )
95
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 MobileNetVaImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=None , ) -> Optional[int]: '''simple docstring''' a__ : str =size if size is not None else {"shortest_edge": 2_0} a__ : Union[str, Any] =crop_size if crop_size is not None else {"height": 1_8, "width": 1_8} a__ : Tuple =parent a__ : Optional[int] =batch_size a__ : Any =num_channels a__ : List[str] =image_size a__ : Dict =min_resolution a__ : List[Any] =max_resolution a__ : Dict =do_resize a__ : Union[str, Any] =size a__ : str =do_center_crop a__ : List[str] =crop_size def _lowercase ( self ) -> str: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : Optional[Any] = MobileNetVaImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =MobileNetVaImageProcessingTester(self ) @property def _lowercase ( self ) -> List[str]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "crop_size" ) ) def _lowercase ( self ) -> str: '''simple docstring''' a__ : Any =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 2_0} ) self.assertEqual(image_processor.crop_size , {"height": 1_8, "width": 1_8} ) a__ : Dict =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 _lowercase ( self ) -> Any: '''simple docstring''' pass def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Dict =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : Optional[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : List[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 a__ : Dict =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> int: '''simple docstring''' a__ : str =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input a__ : List[str] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a__ : Union[str, Any] =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : int =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input a__ : Optional[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 a__ : str =image_processing(lowerCAmelCase__ , 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"], ) , )
95
1
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) UpperCAmelCase : int = { """huggingface/time-series-transformer-tourism-monthly""": ( """https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json""" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Any = """time_series_transformer""" _lowercase : Union[str, Any] = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", """num_hidden_layers""": """encoder_layers""", } def __init__( self , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = "student_t" , lowerCAmelCase__ = "nll" , lowerCAmelCase__ = 1 , lowerCAmelCase__ = [1, 2, 3, 4, 5, 6, 7] , lowerCAmelCase__ = "mean" , lowerCAmelCase__ = 0 , lowerCAmelCase__ = 0 , lowerCAmelCase__ = 0 , lowerCAmelCase__ = 0 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = 3_2 , lowerCAmelCase__ = 3_2 , lowerCAmelCase__ = 2 , lowerCAmelCase__ = 2 , lowerCAmelCase__ = 2 , lowerCAmelCase__ = 2 , lowerCAmelCase__ = True , lowerCAmelCase__ = "gelu" , lowerCAmelCase__ = 6_4 , lowerCAmelCase__ = 0.1 , lowerCAmelCase__ = 0.1 , lowerCAmelCase__ = 0.1 , lowerCAmelCase__ = 0.1 , lowerCAmelCase__ = 0.1 , lowerCAmelCase__ = 1_0_0 , lowerCAmelCase__ = 0.02 , lowerCAmelCase__=True , **lowerCAmelCase__ , ) -> List[str]: '''simple docstring''' a__ : int =prediction_length a__ : List[Any] =context_length or prediction_length a__ : int =distribution_output a__ : List[str] =loss a__ : Optional[int] =input_size a__ : Dict =num_time_features a__ : Any =lags_sequence a__ : List[Any] =scaling a__ : Optional[Any] =num_dynamic_real_features a__ : Dict =num_static_real_features a__ : Optional[int] =num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(lowerCAmelCase__ ) != num_static_categorical_features: raise ValueError( "The cardinality should be a list of the same length as `num_static_categorical_features`" ) a__ : Optional[Any] =cardinality else: a__ : List[Any] =[0] if embedding_dimension and num_static_categorical_features > 0: if len(lowerCAmelCase__ ) != num_static_categorical_features: raise ValueError( "The embedding dimension should be a list of the same length as `num_static_categorical_features`" ) a__ : List[str] =embedding_dimension else: a__ : int =[min(5_0 , (cat + 1) // 2 ) for cat in self.cardinality] a__ : Any =num_parallel_samples # Transformer architecture configuration a__ : Optional[Any] =input_size * len(lowerCAmelCase__ ) + self._number_of_features a__ : str =d_model a__ : List[Any] =encoder_attention_heads a__ : int =decoder_attention_heads a__ : Tuple =encoder_ffn_dim a__ : Optional[Any] =decoder_ffn_dim a__ : Any =encoder_layers a__ : Union[str, Any] =decoder_layers a__ : Optional[int] =dropout a__ : List[str] =attention_dropout a__ : Union[str, Any] =activation_dropout a__ : int =encoder_layerdrop a__ : List[Any] =decoder_layerdrop a__ : str =activation_function a__ : Union[str, Any] =init_std a__ : Optional[Any] =use_cache super().__init__(is_encoder_decoder=lowerCAmelCase__ , **lowerCAmelCase__ ) @property def _lowercase ( self ) -> int: '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
95
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Any = { """configuration_convbert""": ["""CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvBertConfig""", """ConvBertOnnxConfig"""], """tokenization_convbert""": ["""ConvBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] = ["""ConvBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[str] = [ """CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConvBertForMaskedLM""", """ConvBertForMultipleChoice""", """ConvBertForQuestionAnswering""", """ConvBertForSequenceClassification""", """ConvBertForTokenClassification""", """ConvBertLayer""", """ConvBertModel""", """ConvBertPreTrainedModel""", """load_tf_weights_in_convbert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ """TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFConvBertForMaskedLM""", """TFConvBertForMultipleChoice""", """TFConvBertForQuestionAnswering""", """TFConvBertForSequenceClassification""", """TFConvBertForTokenClassification""", """TFConvBertLayer""", """TFConvBertModel""", """TFConvBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
95
1
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : str = ConsistencyModelPipeline _lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_PARAMS _lowercase : Dict = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt _lowercase : Optional[int] = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ]) @property def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : str =UNetaDModel.from_pretrained( "diffusers/consistency-models-test" , subfolder="test_unet" , ) return unet @property def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : List[str] =UNetaDModel.from_pretrained( "diffusers/consistency-models-test" , subfolder="test_unet_class_cond" , ) return unet def _lowercase ( self , lowerCAmelCase__=False ) -> List[str]: '''simple docstring''' if class_cond: a__ : int =self.dummy_cond_unet else: a__ : Union[str, Any] =self.dummy_uncond_unet # Default to CM multistep sampler a__ : int =CMStochasticIterativeScheduler( num_train_timesteps=4_0 , sigma_min=0.0_02 , sigma_max=80.0 , ) a__ : Tuple ={ "unet": unet, "scheduler": scheduler, } return components def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=0 ) -> Any: '''simple docstring''' if str(lowerCAmelCase__ ).startswith("mps" ): a__ : Optional[Any] =torch.manual_seed(lowerCAmelCase__ ) else: a__ : Dict =torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ ) a__ : Optional[int] ={ "batch_size": 1, "num_inference_steps": None, "timesteps": [2_2, 0], "generator": generator, "output_type": "np", } return inputs def _lowercase ( self ) -> int: '''simple docstring''' a__ : Union[str, Any] ="cpu" # ensure determinism for the device-dependent torch.Generator a__ : int =self.get_dummy_components() a__ : Tuple =ConsistencyModelPipeline(**lowerCAmelCase__ ) a__ : Any =pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Any =self.get_dummy_inputs(lowerCAmelCase__ ) a__ : List[Any] =pipe(**lowerCAmelCase__ ).images assert image.shape == (1, 3_2, 3_2, 3) a__ : Union[str, Any] =image[0, -3:, -3:, -1] a__ : Any =np.array([0.35_72, 0.62_73, 0.40_31, 0.39_61, 0.43_21, 0.57_30, 0.52_66, 0.47_80, 0.50_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : Any ="cpu" # ensure determinism for the device-dependent torch.Generator a__ : str =self.get_dummy_components(class_cond=lowerCAmelCase__ ) a__ : Any =ConsistencyModelPipeline(**lowerCAmelCase__ ) a__ : List[str] =pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : List[Any] =self.get_dummy_inputs(lowerCAmelCase__ ) a__ : Any =0 a__ : Optional[int] =pipe(**lowerCAmelCase__ ).images assert image.shape == (1, 3_2, 3_2, 3) a__ : int =image[0, -3:, -3:, -1] a__ : Any =np.array([0.35_72, 0.62_73, 0.40_31, 0.39_61, 0.43_21, 0.57_30, 0.52_66, 0.47_80, 0.50_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : List[Any] ="cpu" # ensure determinism for the device-dependent torch.Generator a__ : Optional[int] =self.get_dummy_components() a__ : Tuple =ConsistencyModelPipeline(**lowerCAmelCase__ ) a__ : List[Any] =pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : str =self.get_dummy_inputs(lowerCAmelCase__ ) a__ : Union[str, Any] =1 a__ : List[Any] =None a__ : List[str] =pipe(**lowerCAmelCase__ ).images assert image.shape == (1, 3_2, 3_2, 3) a__ : Dict =image[0, -3:, -3:, -1] a__ : Any =np.array([0.50_04, 0.50_04, 0.49_94, 0.50_08, 0.49_76, 0.50_18, 0.49_90, 0.49_82, 0.49_87] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[Any] ="cpu" # ensure determinism for the device-dependent torch.Generator a__ : Optional[int] =self.get_dummy_components(class_cond=lowerCAmelCase__ ) a__ : Tuple =ConsistencyModelPipeline(**lowerCAmelCase__ ) a__ : Union[str, Any] =pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Union[str, Any] =self.get_dummy_inputs(lowerCAmelCase__ ) a__ : Dict =1 a__ : List[Any] =None a__ : int =0 a__ : List[str] =pipe(**lowerCAmelCase__ ).images assert image.shape == (1, 3_2, 3_2, 3) a__ : int =image[0, -3:, -3:, -1] a__ : Optional[int] =np.array([0.50_04, 0.50_04, 0.49_94, 0.50_08, 0.49_76, 0.50_18, 0.49_90, 0.49_82, 0.49_87] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self , lowerCAmelCase__=0 , lowerCAmelCase__=False , lowerCAmelCase__="cpu" , lowerCAmelCase__=torch.floataa , lowerCAmelCase__=(1, 3, 6_4, 6_4) ) -> Union[str, Any]: '''simple docstring''' a__ : Any =torch.manual_seed(lowerCAmelCase__ ) a__ : Dict ={ "num_inference_steps": None, "timesteps": [2_2, 0], "class_labels": 0, "generator": generator, "output_type": "np", } if get_fixed_latents: a__ : Union[str, Any] =self.get_fixed_latents(seed=lowerCAmelCase__ , device=lowerCAmelCase__ , dtype=lowerCAmelCase__ , shape=lowerCAmelCase__ ) a__ : Any =latents return inputs def _lowercase ( self , lowerCAmelCase__=0 , lowerCAmelCase__="cpu" , lowerCAmelCase__=torch.floataa , lowerCAmelCase__=(1, 3, 6_4, 6_4) ) -> List[str]: '''simple docstring''' if type(lowerCAmelCase__ ) == str: a__ : List[str] =torch.device(lowerCAmelCase__ ) a__ : str =torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ ) a__ : Any =randn_tensor(lowerCAmelCase__ , generator=lowerCAmelCase__ , device=lowerCAmelCase__ , dtype=lowerCAmelCase__ ) return latents def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[Any] =UNetaDModel.from_pretrained("diffusers/consistency_models" , subfolder="diffusers_cd_imagenet64_l2" ) a__ : Union[str, Any] =CMStochasticIterativeScheduler( num_train_timesteps=4_0 , sigma_min=0.0_02 , sigma_max=80.0 , ) a__ : int =ConsistencyModelPipeline(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ ) pipe.to(torch_device=lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Dict =self.get_inputs() a__ : List[str] =pipe(**lowerCAmelCase__ ).images assert image.shape == (1, 6_4, 6_4, 3) a__ : Any =image[0, -3:, -3:, -1] a__ : Optional[Any] =np.array([0.08_88, 0.08_81, 0.06_66, 0.04_79, 0.02_92, 0.01_95, 0.02_01, 0.01_63, 0.02_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =UNetaDModel.from_pretrained("diffusers/consistency_models" , subfolder="diffusers_cd_imagenet64_l2" ) a__ : str =CMStochasticIterativeScheduler( num_train_timesteps=4_0 , sigma_min=0.0_02 , sigma_max=80.0 , ) a__ : List[Any] =ConsistencyModelPipeline(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ ) pipe.to(torch_device=lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : int =self.get_inputs() a__ : Optional[Any] =1 a__ : Tuple =None a__ : List[str] =pipe(**lowerCAmelCase__ ).images assert image.shape == (1, 6_4, 6_4, 3) a__ : List[str] =image[0, -3:, -3:, -1] a__ : List[Any] =np.array([0.03_40, 0.01_52, 0.00_63, 0.02_67, 0.02_21, 0.01_07, 0.04_16, 0.01_86, 0.02_17] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 @require_torch_a def _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : str =UNetaDModel.from_pretrained("diffusers/consistency_models" , subfolder="diffusers_cd_imagenet64_l2" ) a__ : List[Any] =CMStochasticIterativeScheduler( num_train_timesteps=4_0 , sigma_min=0.0_02 , sigma_max=80.0 , ) a__ : Union[str, Any] =ConsistencyModelPipeline(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ ) pipe.to(torch_device=lowerCAmelCase__ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : List[str] =self.get_inputs(get_fixed_latents=lowerCAmelCase__ , device=lowerCAmelCase__ ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=lowerCAmelCase__ , enable_math=lowerCAmelCase__ , enable_mem_efficient=lowerCAmelCase__ ): a__ : Optional[int] =pipe(**lowerCAmelCase__ ).images assert image.shape == (1, 6_4, 6_4, 3) a__ : str =image[0, -3:, -3:, -1] a__ : Any =np.array([0.18_75, 0.14_28, 0.12_89, 0.21_51, 0.20_92, 0.14_77, 0.18_77, 0.16_41, 0.13_53] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @require_torch_a def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =UNetaDModel.from_pretrained("diffusers/consistency_models" , subfolder="diffusers_cd_imagenet64_l2" ) a__ : Dict =CMStochasticIterativeScheduler( num_train_timesteps=4_0 , sigma_min=0.0_02 , sigma_max=80.0 , ) a__ : Any =ConsistencyModelPipeline(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ ) pipe.to(torch_device=lowerCAmelCase__ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Dict =self.get_inputs(get_fixed_latents=lowerCAmelCase__ , device=lowerCAmelCase__ ) a__ : Optional[Any] =1 a__ : Union[str, Any] =None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=lowerCAmelCase__ , enable_math=lowerCAmelCase__ , enable_mem_efficient=lowerCAmelCase__ ): a__ : Optional[Any] =pipe(**lowerCAmelCase__ ).images assert image.shape == (1, 6_4, 6_4, 3) a__ : int =image[0, -3:, -3:, -1] a__ : int =np.array([0.16_63, 0.19_48, 0.22_75, 0.16_80, 0.12_04, 0.12_45, 0.18_58, 0.13_38, 0.20_95] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
95
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : Tuple = { """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Any = """swin2sr""" _lowercase : Tuple = { """hidden_size""": """embed_dim""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , lowerCAmelCase__=6_4 , lowerCAmelCase__=1 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8_0 , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=8 , lowerCAmelCase__=2.0 , lowerCAmelCase__=True , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__="gelu" , lowerCAmelCase__=False , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-5 , lowerCAmelCase__=2 , lowerCAmelCase__=1.0 , lowerCAmelCase__="1conv" , lowerCAmelCase__="pixelshuffle" , **lowerCAmelCase__ , ) -> int: '''simple docstring''' super().__init__(**lowerCAmelCase__ ) a__ : Optional[Any] =image_size a__ : Dict =patch_size a__ : Tuple =num_channels a__ : Union[str, Any] =embed_dim a__ : Optional[Any] =depths a__ : List[str] =len(lowerCAmelCase__ ) a__ : Any =num_heads a__ : Any =window_size a__ : str =mlp_ratio a__ : List[str] =qkv_bias a__ : Dict =hidden_dropout_prob a__ : List[str] =attention_probs_dropout_prob a__ : Dict =drop_path_rate a__ : Optional[Any] =hidden_act a__ : Union[str, Any] =use_absolute_embeddings a__ : Optional[Any] =layer_norm_eps a__ : List[Any] =initializer_range a__ : int =upscale a__ : Optional[int] =img_range a__ : Any =resi_connection a__ : Optional[Any] =upsampler
95
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : str = logging.get_logger(__name__) UpperCAmelCase : str = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[Any] = """megatron-bert""" def __init__( self , lowerCAmelCase__=2_9_0_5_6 , lowerCAmelCase__=1_0_2_4 , lowerCAmelCase__=2_4 , lowerCAmelCase__=1_6 , lowerCAmelCase__=4_0_9_6 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=0 , lowerCAmelCase__="absolute" , lowerCAmelCase__=True , **lowerCAmelCase__ , ) -> int: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Optional[int] =vocab_size a__ : Any =hidden_size a__ : List[Any] =num_hidden_layers a__ : Optional[int] =num_attention_heads a__ : List[str] =hidden_act a__ : Union[str, Any] =intermediate_size a__ : Optional[int] =hidden_dropout_prob a__ : Tuple =attention_probs_dropout_prob a__ : List[str] =max_position_embeddings a__ : Optional[int] =type_vocab_size a__ : int =initializer_range a__ : Any =layer_norm_eps a__ : List[Any] =position_embedding_type a__ : Dict =use_cache
95
from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class __lowerCAmelCase : pass
95
1
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if len(SCREAMING_SNAKE_CASE ) == 0: return [] a__ , a__ : int =min(SCREAMING_SNAKE_CASE ), max(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =int(max_value - min_value ) + 1 a__ : list[list] =[[] for _ in range(SCREAMING_SNAKE_CASE )] for i in my_list: buckets[int(i - min_value )].append(SCREAMING_SNAKE_CASE ) return [v for bucket in buckets for v in sorted(SCREAMING_SNAKE_CASE )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
95
# 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 __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = """philschmid/bart-large-cnn-samsum""" _lowercase : List[Any] = ( """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.""" ) _lowercase : Any = """summarizer""" _lowercase : Any = AutoTokenizer _lowercase : str = AutoModelForSeqaSeqLM _lowercase : Optional[int] = ["""text"""] _lowercase : Optional[int] = ["""text"""] def _lowercase ( self , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' return self.pre_processor(lowerCAmelCase__ , return_tensors="pt" , truncation=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return self.model.generate(**lowerCAmelCase__ )[0] def _lowercase ( self , lowerCAmelCase__ ) -> Any: '''simple docstring''' return self.pre_processor.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ )
95
1
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("dataset_size" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("input_in_memory_max_size" , ["default", 0, 100 * 2**20, 900 * 2**20] ) def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , "IN_MEMORY_MAX_SIZE" , SCREAMING_SNAKE_CASE ) a__ : Union[str, Any] =datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: a__ : List[str] =dataset_size < in_memory_max_size else: a__ : Any =False a__ : List[str] =is_small_dataset(SCREAMING_SNAKE_CASE ) assert result == expected
95
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer UpperCAmelCase : int = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase : List[Any] = [ """small""", """small-base""", """medium""", """medium-base""", """intermediate""", """intermediate-base""", """large""", """large-base""", """xlarge""", """xlarge-base""", ] UpperCAmelCase : Optional[int] = { """vocab_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt""", """funnel-transformer/small-base""": """https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt""", """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt""", """funnel-transformer/large-base""": """https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt""", """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json""", """funnel-transformer/small-base""": ( """https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json""" ), """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json""", """funnel-transformer/large-base""": ( """https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json""" ), """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json""" ), }, } UpperCAmelCase : Optional[int] = {F"""funnel-transformer/{name}""": 512 for name in _model_names} UpperCAmelCase : Optional[int] = {F"""funnel-transformer/{name}""": {"""do_lower_case""": True} for name in _model_names} class __lowerCAmelCase ( UpperCamelCase__): _lowercase : str = VOCAB_FILES_NAMES _lowercase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowercase : Dict = PRETRAINED_INIT_CONFIGURATION _lowercase : Union[str, Any] = FunnelTokenizer _lowercase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : int = 2 def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<sep>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="<cls>" , lowerCAmelCase__="<mask>" , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__="##" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , clean_text=lowerCAmelCase__ , tokenize_chinese_chars=lowerCAmelCase__ , strip_accents=lowerCAmelCase__ , wordpieces_prefix=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : Optional[Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowerCAmelCase__ ) != do_lower_case or normalizer_state.get("strip_accents" , lowerCAmelCase__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowerCAmelCase__ ) != tokenize_chinese_chars ): a__ : List[str] =getattr(lowerCAmelCase__ , normalizer_state.pop("type" ) ) a__ : Union[str, Any] =do_lower_case a__ : Any =strip_accents a__ : Optional[Any] =tokenize_chinese_chars a__ : Dict =normalizer_class(**lowerCAmelCase__ ) a__ : Any =do_lower_case def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> str: '''simple docstring''' a__ : Dict =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] =[self.sep_token_id] a__ : Union[str, Any] =[self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: '''simple docstring''' a__ : Tuple =self._tokenizer.model.save(lowerCAmelCase__ , name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ )
95
1
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase : str = logging.get_logger(__name__) UpperCAmelCase : Dict = {"""vocab_file""": """vocab.json"""} UpperCAmelCase : Optional[int] = { """vocab_file""": { """mgp-str""": """https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json""", } } UpperCAmelCase : Tuple = {"""mgp-str""": 27} class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : Any = PRETRAINED_VOCAB_FILES_MAP _lowercase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , lowerCAmelCase__ , lowerCAmelCase__="[GO]" , lowerCAmelCase__="[GO]" , lowerCAmelCase__="[s]" , lowerCAmelCase__="[GO]" , **lowerCAmelCase__ ) -> List[str]: '''simple docstring''' super().__init__( unk_token=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , **lowerCAmelCase__ , ) with open(lowerCAmelCase__ , encoding="utf-8" ) as vocab_handle: a__ : List[str] =json.load(lowerCAmelCase__ ) a__ : int ={v: k for k, v in self.vocab.items()} @property def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' return len(self.vocab ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' return dict(self.vocab , **self.added_tokens_encoder ) def _lowercase ( self , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' a__ : List[Any] =[] for s in text: char_tokens.extend(lowerCAmelCase__ ) return char_tokens def _lowercase ( self , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' return self.vocab.get(lowerCAmelCase__ , self.vocab.get(self.unk_token ) ) def _lowercase ( self , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' return self.decoder.get(lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(lowerCAmelCase__ ): logger.error("Vocabulary path ({}) should be a directory".format(lowerCAmelCase__ ) ) return a__ : Union[str, Any] =os.path.join( lowerCAmelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) with open(lowerCAmelCase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=lowerCAmelCase__ , ensure_ascii=lowerCAmelCase__ ) + "\n" ) return (vocab_file,)
95
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 ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = "arrow" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( split=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ , streaming=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : int =load_from_cache_file a__ : Tuple =file_format a__ : List[Any] =Spark( df=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , working_dir=lowerCAmelCase__ , **lowerCAmelCase__ , ) def _lowercase ( self ) -> str: '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) a__ : str =None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowerCAmelCase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
95
1
import copy from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging UpperCAmelCase : List[Any] = logging.get_logger(__name__) class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = ["""input_features"""] def __init__( self , lowerCAmelCase__=8_0 , lowerCAmelCase__=1_6_0_0_0 , lowerCAmelCase__=1_6_0 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=False , **lowerCAmelCase__ , ) -> Tuple: '''simple docstring''' super().__init__( feature_size=lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , padding_value=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : Any =n_fft a__ : List[Any] =hop_length a__ : Any =chunk_length a__ : List[Any] =chunk_length * sampling_rate a__ : Tuple =self.n_samples // hop_length a__ : str =sampling_rate a__ : Dict =mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=lowerCAmelCase__ , min_frequency=0.0 , max_frequency=80_00.0 , sampling_rate=lowerCAmelCase__ , norm="slaney" , mel_scale="slaney" , ) def _lowercase ( self , lowerCAmelCase__ ) -> np.ndarray: '''simple docstring''' a__ : Tuple =spectrogram( lowerCAmelCase__ , window_function(self.n_fft , "hann" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel="log10" , ) a__ : List[Any] =log_spec[:, :-1] a__ : Optional[int] =np.maximum(lowerCAmelCase__ , log_spec.max() - 8.0 ) a__ : Optional[Any] =(log_spec + 4.0) / 4.0 return log_spec @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def _lowercase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 0.0 ) -> List[np.ndarray]: '''simple docstring''' if attention_mask is not None: a__ : Union[str, Any] =np.array(lowerCAmelCase__ , np.intaa ) a__ : str =[] for vector, length in zip(lowerCAmelCase__ , attention_mask.sum(-1 ) ): a__ : Union[str, Any] =(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7 ) if length < normed_slice.shape[0]: a__ : Union[str, Any] =padding_value normed_input_values.append(lowerCAmelCase__ ) else: a__ : Tuple =[(x - x.mean()) / np.sqrt(x.var() + 1E-7 ) for x in input_values] return normed_input_values def __call__( self , lowerCAmelCase__ , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = "max_length" , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , **lowerCAmelCase__ , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a''' F''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input''' F''' was sampled with {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( "It is strongly recommended to pass the `sampling_rate` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug." ) a__ : Union[str, Any] =isinstance(lowerCAmelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F'''Only mono-channel audio is supported for input to {self}''' ) a__ : List[Any] =is_batched_numpy or ( isinstance(lowerCAmelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: a__ : List[str] =[np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(lowerCAmelCase__ , np.ndarray ): a__ : Union[str, Any] =np.asarray(lowerCAmelCase__ , dtype=np.floataa ) elif isinstance(lowerCAmelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): a__ : Union[str, Any] =raw_speech.astype(np.floataa ) # always return batch if not is_batched: a__ : Union[str, Any] =[np.asarray([raw_speech] ).T] a__ : Optional[Any] =BatchFeature({"input_features": raw_speech} ) # convert into correct format for padding a__ : List[str] =self.pad( lowerCAmelCase__ , padding=lowerCAmelCase__ , max_length=max_length if max_length else self.n_samples , truncation=lowerCAmelCase__ , pad_to_multiple_of=lowerCAmelCase__ , return_attention_mask=return_attention_mask or do_normalize , ) # zero-mean and unit-variance normalization if do_normalize: a__ : List[str] =self.zero_mean_unit_var_norm( padded_inputs["input_features"] , attention_mask=padded_inputs["attention_mask"] , padding_value=self.padding_value , ) a__ : Tuple =np.stack(padded_inputs["input_features"] , axis=0 ) # make sure list is in array format a__ : int =padded_inputs.get("input_features" ).transpose(2 , 0 , 1 ) a__ : Optional[Any] =[self._np_extract_fbank_features(lowerCAmelCase__ ) for waveform in input_features[0]] if isinstance(input_features[0] , lowerCAmelCase__ ): a__ : Dict =[np.asarray(lowerCAmelCase__ , dtype=np.floataa ) for feature in input_features] else: a__ : int =input_features if return_attention_mask: # rescale from sample (48000) to feature (3000) a__ : Optional[int] =padded_inputs["attention_mask"][:, :: self.hop_length] if return_tensors is not None: a__ : Optional[int] =padded_inputs.convert_to_tensors(lowerCAmelCase__ ) return padded_inputs def _lowercase ( self ) -> Dict[str, Any]: '''simple docstring''' a__ : List[Any] =copy.deepcopy(self.__dict__ ) a__ : Optional[int] =self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] return output
95
from math import pi def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
95
1
import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[Any] ="| <pad> <unk> <s> </s> a b c d e f g h i j k".split() a__ : Optional[Any] =dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) a__ : Optional[Any] ={ "unk_token": "<unk>", "bos_token": "<s>", "eos_token": "</s>", } a__ : Tuple ={ "feature_size": 1, "padding_value": 0.0, "sampling_rate": 1_6_0_0_0, "return_attention_mask": False, "do_normalize": True, } a__ : List[str] =tempfile.mkdtemp() a__ : List[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) a__ : int =os.path.join(self.tmpdirname , lowerCAmelCase__ ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowerCAmelCase__ ) + "\n" ) with open(self.feature_extraction_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowerCAmelCase__ ) + "\n" ) # load decoder from hub a__ : str ="hf-internal-testing/ngram-beam-search-decoder" def _lowercase ( self , **lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' a__ : List[str] =self.add_kwargs_tokens_map.copy() kwargs.update(lowerCAmelCase__ ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> List[str]: '''simple docstring''' return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **lowerCAmelCase__ ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Any =self.get_tokenizer() a__ : str =self.get_feature_extractor() a__ : Tuple =self.get_decoder() a__ : Optional[Any] =WavaVecaProcessorWithLM(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__ , decoder=lowerCAmelCase__ ) processor.save_pretrained(self.tmpdirname ) a__ : List[Any] =WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , lowerCAmelCase__ ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , lowerCAmelCase__ ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , lowerCAmelCase__ ) def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : Optional[int] =WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match a__ : Tuple =WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[Any] =self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(["xx"] ) with self.assertRaisesRegex(lowerCAmelCase__ , "include" ): WavaVecaProcessorWithLM( tokenizer=lowerCAmelCase__ , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : List[Any] =self.get_feature_extractor() a__ : List[Any] =self.get_tokenizer() a__ : List[str] =self.get_decoder() a__ : Optional[Any] =WavaVecaProcessorWithLM(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__ , decoder=lowerCAmelCase__ ) a__ : Optional[int] =floats_list((3, 1_0_0_0) ) a__ : int =feature_extractor(lowerCAmelCase__ , return_tensors="np" ) a__ : Union[str, Any] =processor(lowerCAmelCase__ , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =self.get_feature_extractor() a__ : int =self.get_tokenizer() a__ : Any =self.get_decoder() a__ : Tuple =WavaVecaProcessorWithLM(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__ , decoder=lowerCAmelCase__ ) a__ : List[str] ="This is a test string" a__ : Optional[int] =processor(text=lowerCAmelCase__ ) a__ : Any =tokenizer(lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowercase ( self , lowerCAmelCase__=(2, 1_0, 1_6) , lowerCAmelCase__=7_7 ) -> Dict: '''simple docstring''' np.random.seed(lowerCAmelCase__ ) return np.random.rand(*lowerCAmelCase__ ) def _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : Optional[int] =self.get_feature_extractor() a__ : Optional[Any] =self.get_tokenizer() a__ : Union[str, Any] =self.get_decoder() a__ : Tuple =WavaVecaProcessorWithLM(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__ , decoder=lowerCAmelCase__ ) a__ : int =self._get_dummy_logits(shape=(1_0, 1_6) , seed=1_3 ) a__ : int =processor.decode(lowerCAmelCase__ ) a__ : Optional[Any] =decoder.decode_beams(lowerCAmelCase__ )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual("</s> <s> </s>" , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ["fork"], ["spawn"]] ) def _lowercase ( self , lowerCAmelCase__ ) -> Dict: '''simple docstring''' a__ : Dict =self.get_feature_extractor() a__ : Union[str, Any] =self.get_tokenizer() a__ : Union[str, Any] =self.get_decoder() a__ : Optional[int] =WavaVecaProcessorWithLM(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__ , decoder=lowerCAmelCase__ ) a__ : List[Any] =self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: a__ : List[Any] =processor.batch_decode(lowerCAmelCase__ ) else: with get_context(lowerCAmelCase__ ).Pool() as pool: a__ : Tuple =processor.batch_decode(lowerCAmelCase__ , lowerCAmelCase__ ) a__ : Optional[int] =list(lowerCAmelCase__ ) with get_context("fork" ).Pool() as p: a__ : Any =decoder.decode_beams_batch(lowerCAmelCase__ , lowerCAmelCase__ ) a__ , a__ , a__ : Any =[], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(lowerCAmelCase__ , decoded_processor.text ) self.assertListEqual(["<s> <s> </s>", "<s> <s> <s>"] , decoded_processor.text ) self.assertListEqual(lowerCAmelCase__ , decoded_processor.logit_score ) self.assertListEqual(lowerCAmelCase__ , decoded_processor.lm_score ) def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : Optional[Any] =self.get_feature_extractor() a__ : Optional[Any] =self.get_tokenizer() a__ : Union[str, Any] =self.get_decoder() a__ : List[str] =WavaVecaProcessorWithLM(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__ , decoder=lowerCAmelCase__ ) a__ : Optional[Any] =self._get_dummy_logits() a__ : List[Any] =1_5 a__ : List[Any] =-20.0 a__ : str =-4.0 a__ : Union[str, Any] =processor.batch_decode( lowerCAmelCase__ , beam_width=lowerCAmelCase__ , beam_prune_logp=lowerCAmelCase__ , token_min_logp=lowerCAmelCase__ , ) a__ : List[str] =decoded_processor_out.text a__ : List[Any] =list(lowerCAmelCase__ ) with get_context("fork" ).Pool() as pool: a__ : Dict =decoder.decode_beams_batch( lowerCAmelCase__ , lowerCAmelCase__ , beam_width=lowerCAmelCase__ , beam_prune_logp=lowerCAmelCase__ , token_min_logp=lowerCAmelCase__ , ) a__ : str =[d[0][0] for d in decoded_decoder_out] a__ : List[Any] =[d[0][2] for d in decoded_decoder_out] a__ : List[Any] =[d[0][3] for d in decoded_decoder_out] self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) self.assertListEqual(["</s> <s> <s>", "<s> <s> <s>"] , lowerCAmelCase__ ) self.assertTrue(np.array_equal(lowerCAmelCase__ , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.0_54, -18.4_47] , lowerCAmelCase__ , atol=1E-3 ) ) self.assertTrue(np.array_equal(lowerCAmelCase__ , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.5_54, -13.94_74] , lowerCAmelCase__ , atol=1E-3 ) ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] =self.get_feature_extractor() a__ : List[Any] =self.get_tokenizer() a__ : Optional[int] =self.get_decoder() a__ : Dict =WavaVecaProcessorWithLM(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__ , decoder=lowerCAmelCase__ ) a__ : List[Any] =self._get_dummy_logits() a__ : Dict =2.0 a__ : int =5.0 a__ : str =-20.0 a__ : Tuple =True a__ : Tuple =processor.batch_decode( lowerCAmelCase__ , alpha=lowerCAmelCase__ , beta=lowerCAmelCase__ , unk_score_offset=lowerCAmelCase__ , lm_score_boundary=lowerCAmelCase__ , ) a__ : Union[str, Any] =decoded_processor_out.text a__ : Tuple =list(lowerCAmelCase__ ) decoder.reset_params( alpha=lowerCAmelCase__ , beta=lowerCAmelCase__ , unk_score_offset=lowerCAmelCase__ , lm_score_boundary=lowerCAmelCase__ , ) with get_context("fork" ).Pool() as pool: a__ : str =decoder.decode_beams_batch( lowerCAmelCase__ , lowerCAmelCase__ , ) a__ : Optional[Any] =[d[0][0] for d in decoded_decoder_out] self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) self.assertListEqual(["<s> </s> <s> </s> </s>", "</s> </s> <s> </s> </s>"] , lowerCAmelCase__ ) a__ : Dict =processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -20.0 ) self.assertEqual(lm_model.score_boundary , lowerCAmelCase__ ) def _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : Any =WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) a__ : Dict =processor.decoder.model_container[processor.decoder._model_key] a__ : Dict =Path(language_model._kenlm_model.path.decode("utf-8" ) ).parent.parent.absolute() a__ : Union[str, Any] =os.listdir(lowerCAmelCase__ ) a__ : Tuple =["alphabet.json", "language_model"] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : List[str] =snapshot_download("hf-internal-testing/processor_with_lm" ) a__ : Union[str, Any] =WavaVecaProcessorWithLM.from_pretrained(lowerCAmelCase__ ) a__ : List[Any] =processor.decoder.model_container[processor.decoder._model_key] a__ : str =Path(language_model._kenlm_model.path.decode("utf-8" ) ).parent.parent.absolute() a__ : List[str] =os.listdir(lowerCAmelCase__ ) a__ : Optional[Any] =os.listdir(lowerCAmelCase__ ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : Dict =WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) a__ : str =AutoProcessor.from_pretrained("hf-internal-testing/processor_with_lm" ) a__ : str =floats_list((3, 1_0_0_0) ) a__ : int =processor_wavaveca(lowerCAmelCase__ , return_tensors="np" ) a__ : List[Any] =processor_auto(lowerCAmelCase__ , return_tensors="np" ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1E-2 ) a__ : int =self._get_dummy_logits() a__ : Tuple =processor_wavaveca.batch_decode(lowerCAmelCase__ ) a__ : int =processor_auto.batch_decode(lowerCAmelCase__ ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =self.get_feature_extractor() a__ : List[Any] =self.get_tokenizer() a__ : Dict =self.get_decoder() a__ : Tuple =WavaVecaProcessorWithLM(tokenizer=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__ , decoder=lowerCAmelCase__ ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , ) @staticmethod def _lowercase ( lowerCAmelCase__ , lowerCAmelCase__ ) -> Any: '''simple docstring''' a__ : List[Any] =[d[key] for d in offsets] return retrieved_list def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) a__ : Tuple =self._get_dummy_logits()[0] a__ : Union[str, Any] =processor.decode(lowerCAmelCase__ , output_word_offsets=lowerCAmelCase__ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("text" in outputs ) self.assertTrue("word_offsets" in outputs ) self.assertTrue(isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) ) self.assertEqual(" ".join(self.get_from_offsets(outputs["word_offsets"] , "word" ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "word" ) , ["<s>", "<s>", "</s>"] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "start_offset" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "end_offset" ) , [1, 3, 5] ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : Dict =WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) a__ : List[str] =self._get_dummy_logits() a__ : Union[str, Any] =processor.batch_decode(lowerCAmelCase__ , output_word_offsets=lowerCAmelCase__ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("text" in outputs ) self.assertTrue("word_offsets" in outputs ) self.assertTrue(isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) ) self.assertListEqual( [" ".join(self.get_from_offsets(lowerCAmelCase__ , "word" ) ) for o in outputs["word_offsets"]] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "word" ) , ["<s>", "<s>", "</s>"] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "start_offset" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "end_offset" ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def _lowercase ( self ) -> Tuple: '''simple docstring''' import torch a__ : Optional[Any] =load_dataset("common_voice" , "en" , split="train" , streaming=lowerCAmelCase__ ) a__ : int =ds.cast_column("audio" , datasets.Audio(sampling_rate=1_6_0_0_0 ) ) a__ : List[str] =iter(lowerCAmelCase__ ) a__ : Optional[int] =next(lowerCAmelCase__ ) a__ : Optional[Any] =AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm" ) a__ : Optional[int] =WavaVecaForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm" ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train a__ : Any =processor(sample["audio"]["array"] , return_tensors="pt" ).input_values with torch.no_grad(): a__ : Tuple =model(lowerCAmelCase__ ).logits.cpu().numpy() a__ : Optional[int] =processor.decode(logits[0] , output_word_offsets=lowerCAmelCase__ ) a__ : int =model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate a__ : int =[ { "start_time": d["start_offset"] * time_offset, "end_time": d["end_offset"] * time_offset, "word": d["word"], } for d in output["word_offsets"] ] a__ : Tuple ="WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL" # output words self.assertEqual(" ".join(self.get_from_offsets(lowerCAmelCase__ , "word" ) ) , lowerCAmelCase__ ) self.assertEqual(" ".join(self.get_from_offsets(lowerCAmelCase__ , "word" ) ) , output.text ) # output times a__ : Dict =torch.tensor(self.get_from_offsets(lowerCAmelCase__ , "start_time" ) ) a__ : str =torch.tensor(self.get_from_offsets(lowerCAmelCase__ , "end_time" ) ) # fmt: off a__ : Dict =torch.tensor([1.41_99, 1.65_99, 2.25_99, 3.0, 3.24, 3.59_99, 3.79_99, 4.09_99, 4.26, 4.94, 5.28, 5.65_99, 5.78, 5.94, 6.32, 6.53_99, 6.65_99] ) a__ : int =torch.tensor([1.53_99, 1.89_99, 2.9, 3.16, 3.53_99, 3.72, 4.01_99, 4.17_99, 4.76, 5.15_99, 5.55_99, 5.69_99, 5.86, 6.19_99, 6.38, 6.61_99, 6.94] ) # fmt: on self.assertTrue(torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=0.01 ) ) self.assertTrue(torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=0.01 ) )
95
import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging UpperCAmelCase : int = { """cola""": 2, """mnli""": 3, """mrpc""": 2, """sst-2""": 2, """sts-b""": 1, """qqp""": 2, """qnli""": 2, """rte""": 2, """wnli""": 2, } logging.set_verbosity_info() def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any]=None ): """simple docstring""" a__ : Optional[int] =XLNetConfig.from_json_file(SCREAMING_SNAKE_CASE ) a__ : Dict =finetuning_task.lower() if finetuning_task is not None else "" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(f'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}''' ) a__ : List[str] =finetuning_task a__ : Tuple =GLUE_TASKS_NUM_LABELS[finetuning_task] a__ : List[Any] =XLNetForSequenceClassification(SCREAMING_SNAKE_CASE ) elif "squad" in finetuning_task: a__ : Optional[int] =finetuning_task a__ : Dict =XLNetForQuestionAnswering(SCREAMING_SNAKE_CASE ) else: a__ : List[Any] =XLNetLMHeadModel(SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Save pytorch-model a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print(f'''Save PyTorch model to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE ) print(f'''Save configuration file to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--xlnet_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained XLNet model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the folder to store the PyTorch model or dataset/vocab.""", ) parser.add_argument( """--finetuning_task""", default=None, type=str, help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""", ) UpperCAmelCase : int = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
95
1
def _A ( SCREAMING_SNAKE_CASE : int = 2_000_000 ): """simple docstring""" a__ : Optional[int] =[0 for i in range(n + 1 )] a__ : Dict =1 a__ : List[str] =1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , SCREAMING_SNAKE_CASE ): a__ : List[str] =1 a__ : str =0 for i in range(SCREAMING_SNAKE_CASE ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(F"""{solution() = }""")
95
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { """google/canine-s""": """https://huggingface.co/google/canine-s/resolve/main/config.json""", # See all CANINE models at https://huggingface.co/models?filter=canine } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[Any] = """canine""" def __init__( self , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_6 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=0 , lowerCAmelCase__=0XE0_00 , lowerCAmelCase__=0XE0_01 , lowerCAmelCase__=4 , lowerCAmelCase__=4 , lowerCAmelCase__=8 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_2_8 , **lowerCAmelCase__ , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Optional[int] =max_position_embeddings a__ : str =hidden_size a__ : Optional[Any] =num_hidden_layers a__ : Tuple =num_attention_heads a__ : Optional[Any] =intermediate_size a__ : Optional[int] =hidden_act a__ : List[Any] =hidden_dropout_prob a__ : Union[str, Any] =attention_probs_dropout_prob a__ : Optional[Any] =initializer_range a__ : Union[str, Any] =type_vocab_size a__ : Optional[int] =layer_norm_eps # Character config: a__ : int =downsampling_rate a__ : Optional[Any] =upsampling_kernel_size a__ : Union[str, Any] =num_hash_functions a__ : Any =num_hash_buckets a__ : int =local_transformer_stride
95
1
from math import isqrt, loga def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Optional[Any] =[True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): a__ : List[Any] =False return [i for i in range(2 , SCREAMING_SNAKE_CASE ) if is_prime[i]] def _A ( SCREAMING_SNAKE_CASE : int = 800_800 , SCREAMING_SNAKE_CASE : int = 800_800 ): """simple docstring""" a__ : Union[str, Any] =degree * loga(SCREAMING_SNAKE_CASE ) a__ : List[str] =int(SCREAMING_SNAKE_CASE ) a__ : List[Any] =calculate_prime_numbers(SCREAMING_SNAKE_CASE ) a__ : Dict =0 a__ : int =0 a__ : Optional[int] =len(SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(F"""{solution() = }""")
95
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device UpperCAmelCase : int = False class __lowerCAmelCase ( unittest.TestCase): pass @nightly @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Optional[Any] =torch.manual_seed(0 ) a__ : Optional[Any] =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCAmelCase__ ) a__ : str =VersatileDiffusionPipeline.from_pretrained(lowerCAmelCase__ , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] =generator.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] ="cyberpunk 2077" a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Union[str, Any] =torch.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images a__ : int =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : str ="A painting of a squirrel eating a burger " a__ : Optional[int] =torch.manual_seed(0 ) a__ : str =pipe.text_to_image( prompt=lowerCAmelCase__ , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" ).images a__ : Any =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Optional[int] =np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : Optional[Any] =pipe.image_variation(lowerCAmelCase__ , generator=lowerCAmelCase__ , output_type="numpy" ).images a__ : Union[str, Any] =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
95
1
def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) if len(SCREAMING_SNAKE_CASE ) == 1: return True a__ : Union[str, Any] =series[1] - series[0] for index in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) a__ : Any =0 for val in series: answer += val return answer / len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
95
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class __lowerCAmelCase : def _lowercase ( self , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError() def _lowercase ( self ) -> int: '''simple docstring''' raise NotImplementedError() class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , **lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : str =tokenizer a__ : List[str] =skip_prompt a__ : List[Any] =decode_kwargs # variables used in the streaming process a__ : Dict =[] a__ : int =0 a__ : str =True def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError("TextStreamer only supports batch size 1" ) elif len(value.shape ) > 1: a__ : Any =value[0] if self.skip_prompt and self.next_tokens_are_prompt: a__ : Dict =False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith("\n" ): a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 # If the last token is a CJK character, we print the characters. elif len(lowerCAmelCase__ ) > 0 and self._is_chinese_char(ord(text[-1] ) ): a__ : List[str] =text[self.print_len :] self.print_len += len(lowerCAmelCase__ ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: a__ : str =text[self.print_len : text.rfind(" " ) + 1] self.print_len += len(lowerCAmelCase__ ) self.on_finalized_text(lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' if len(self.token_cache ) > 0: a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 else: a__ : Union[str, Any] ="" a__ : Any =True self.on_finalized_text(lowerCAmelCase__ , stream_end=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> Optional[Any]: '''simple docstring''' print(lowerCAmelCase__ , flush=lowerCAmelCase__ , end="" if not stream_end else None ) def _lowercase ( self , lowerCAmelCase__ ) -> str: '''simple docstring''' if ( (cp >= 0X4E_00 and cp <= 0X9F_FF) or (cp >= 0X34_00 and cp <= 0X4D_BF) # or (cp >= 0X2_00_00 and cp <= 0X2_A6_DF) # or (cp >= 0X2_A7_00 and cp <= 0X2_B7_3F) # or (cp >= 0X2_B7_40 and cp <= 0X2_B8_1F) # or (cp >= 0X2_B8_20 and cp <= 0X2_CE_AF) # or (cp >= 0XF9_00 and cp <= 0XFA_FF) or (cp >= 0X2_F8_00 and cp <= 0X2_FA_1F) # ): # return True return False class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , lowerCAmelCase__ = None , **lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' super().__init__(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : str =Queue() a__ : Optional[Any] =None a__ : Any =timeout def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> List[str]: '''simple docstring''' self.text_queue.put(lowerCAmelCase__ , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self ) -> Dict: '''simple docstring''' return self def _lowercase ( self ) -> int: '''simple docstring''' a__ : int =self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
95
1
from __future__ import annotations class __lowerCAmelCase : def __init__( self , lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : Optional[Any] =TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same number of values, each of which must be of type " "int or float." ) if len(lowerCAmelCase__ ) != 0: a__ : str =len(rows[0] ) if cols == 0: raise error for row in rows: if len(lowerCAmelCase__ ) != cols: raise error for value in row: if not isinstance(lowerCAmelCase__ , (int, float) ): raise error a__ : Union[str, Any] =rows else: a__ : List[Any] =[] def _lowercase ( self ) -> list[list[int]]: '''simple docstring''' return [[row[i] for row in self.rows] for i in range(len(self.rows[0] ) )] @property def _lowercase ( self ) -> int: '''simple docstring''' return len(self.rows ) @property def _lowercase ( self ) -> int: '''simple docstring''' return len(self.rows[0] ) @property def _lowercase ( self ) -> tuple[int, int]: '''simple docstring''' return (self.num_rows, self.num_columns) @property def _lowercase ( self ) -> bool: '''simple docstring''' return self.order[0] == self.order[1] def _lowercase ( self ) -> Matrix: '''simple docstring''' a__ : Any =[ [0 if column_num != row_num else 1 for column_num in range(self.num_rows )] for row_num in range(self.num_rows ) ] return Matrix(lowerCAmelCase__ ) def _lowercase ( self ) -> int: '''simple docstring''' if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0] ) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns ) ) def _lowercase ( self ) -> bool: '''simple docstring''' return bool(self.determinant() ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : int =[ [ self.rows[other_row][other_column] for other_column in range(self.num_columns ) if other_column != column ] for other_row in range(self.num_rows ) if other_row != row ] return Matrix(lowerCAmelCase__ ).determinant() def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: '''simple docstring''' if (row + column) % 2 == 0: return self.get_minor(lowerCAmelCase__ , lowerCAmelCase__ ) return -1 * self.get_minor(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self ) -> Matrix: '''simple docstring''' return Matrix( [ [self.get_minor(lowerCAmelCase__ , lowerCAmelCase__ ) for column in range(self.num_columns )] for row in range(self.num_rows ) ] ) def _lowercase ( self ) -> Matrix: '''simple docstring''' return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns ) ] for row in range(self.minors().num_rows ) ] ) def _lowercase ( self ) -> Matrix: '''simple docstring''' a__ : Tuple =[ [self.cofactors().rows[column][row] for column in range(self.num_columns )] for row in range(self.num_rows ) ] return Matrix(lowerCAmelCase__ ) def _lowercase ( self ) -> Matrix: '''simple docstring''' a__ : List[Any] =self.determinant() if not determinant: raise TypeError("Only matrices with a non-zero determinant have an inverse" ) return self.adjugate() * (1 / determinant) def __repr__( self ) -> str: '''simple docstring''' return str(self.rows ) def __str__( self ) -> str: '''simple docstring''' if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0] ) ) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(lowerCAmelCase__ ) for value in row] ) + ".]" for row in self.rows ] ) + "]" ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> None: '''simple docstring''' a__ : Union[str, Any] =TypeError("Row must be a list containing all ints and/or floats" ) if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise type_error for value in row: if not isinstance(lowerCAmelCase__ , (int, float) ): raise type_error if len(lowerCAmelCase__ ) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(lowerCAmelCase__ ) else: a__ : Optional[int] =self.rows[0:position] + [row] + self.rows[position:] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> None: '''simple docstring''' a__ : Tuple =TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise type_error for value in column: if not isinstance(lowerCAmelCase__ , (int, float) ): raise type_error if len(lowerCAmelCase__ ) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: a__ : Union[str, Any] =[self.rows[i] + [column[i]] for i in range(self.num_rows )] else: a__ : Dict =[ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows ) ] def __eq__( self , lowerCAmelCase__ ) -> bool: '''simple docstring''' if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): return NotImplemented return self.rows == other.rows def __ne__( self , lowerCAmelCase__ ) -> bool: '''simple docstring''' return not self == other def __neg__( self ) -> Matrix: '''simple docstring''' return self * -1 def __add__( self , lowerCAmelCase__ ) -> Matrix: '''simple docstring''' if self.order != other.order: raise ValueError("Addition requires matrices of the same order" ) return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __sub__( self , lowerCAmelCase__ ) -> Matrix: '''simple docstring''' if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order" ) return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __mul__( self , lowerCAmelCase__ ) -> Matrix: '''simple docstring''' if isinstance(lowerCAmelCase__ , (int, float) ): return Matrix( [[int(element * other ) for element in row] for row in self.rows] ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must " "be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(lowerCAmelCase__ , lowerCAmelCase__ ) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) def __pow__( self , lowerCAmelCase__ ) -> Matrix: '''simple docstring''' if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError("A Matrix can only be raised to the power of an int" ) if not self.is_square: raise ValueError("Only square matrices can be raised to a power" ) if other == 0: return self.identity() if other < 0: if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) a__ : List[str] =self for _ in range(other - 1 ): result *= self return result @classmethod def _lowercase ( cls , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: '''simple docstring''' return sum(row[i] * column[i] for i in range(len(lowerCAmelCase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
95
def _A ( SCREAMING_SNAKE_CASE : int = 50 ): """simple docstring""" a__ : Any =[1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
95
1
import argparse from collections import defaultdict def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" a__ : List[Any] =f'''{file}_{class_name}_{test_name}''' done_test[_id] += 1 with open(SCREAMING_SNAKE_CASE , "r" ) as f: a__ : Optional[int] =f.readlines() a__ : List[str] =f'''class {class_name}(''' a__ : List[Any] =f'''{4 * " "}def {test_name}(''' a__ : Optional[int] =f'''{8 * " "}{correct_line.split()[0]}''' a__ : List[Any] =f'''{16 * " "}{correct_line.split()[0]}''' a__ : Dict =False a__ : Dict =False a__ : Dict =False a__ : List[str] =False a__ : int =0 a__ : str =0 a__ : str =[] for line in lines: if line.startswith(SCREAMING_SNAKE_CASE ): a__ : Optional[int] =True elif in_class and line.startswith(SCREAMING_SNAKE_CASE ): a__ : Union[str, Any] =True elif in_class and in_func and (line.startswith(SCREAMING_SNAKE_CASE ) or line.startswith(SCREAMING_SNAKE_CASE )): a__ : Union[str, Any] =len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: a__ : Dict =True if in_class and in_func and in_line: if ")" not in line: continue else: a__ : int =True if in_class and in_func and in_line and insert_line: new_lines.append(f'''{spaces * " "}{correct_line}''' ) a__ : Tuple =False else: new_lines.append(SCREAMING_SNAKE_CASE ) with open(SCREAMING_SNAKE_CASE , "w" ) as f: for line in new_lines: f.write(SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Dict=None ): """simple docstring""" if fail is not None: with open(SCREAMING_SNAKE_CASE , "r" ) as f: a__ : str ={l.strip() for l in f.readlines()} else: a__ : str =None with open(SCREAMING_SNAKE_CASE , "r" ) as f: a__ : List[str] =f.readlines() a__ : int =defaultdict(SCREAMING_SNAKE_CASE ) for line in correct_lines: a__ , a__ , a__ , a__ : List[Any] =line.split(";" ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCAmelCase : str = argparse.ArgumentParser() parser.add_argument("""--correct_filename""", help="""filename of tests with expected result""") parser.add_argument("""--fail_filename""", help="""filename of test failures""", type=str, default=None) UpperCAmelCase : str = parser.parse_args() main(args.correct_filename, args.fail_filename)
95
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if len(SCREAMING_SNAKE_CASE ) == 0: return [] a__ , a__ : int =min(SCREAMING_SNAKE_CASE ), max(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =int(max_value - min_value ) + 1 a__ : list[list] =[[] for _ in range(SCREAMING_SNAKE_CASE )] for i in my_list: buckets[int(i - min_value )].append(SCREAMING_SNAKE_CASE ) return [v for bucket in buckets for v in sorted(SCREAMING_SNAKE_CASE )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
95
1
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase : Union[str, Any] = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """encoder.layer_norm_for_extract""": """layer_norm_for_extract""", """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""", """label_embs_concat""": """label_embeddings_concat""", """mask_emb""": """masked_spec_embed""", """spk_proj""": """speaker_proj""", } UpperCAmelCase : List[Any] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """label_embeddings_concat""", """speaker_proj""", """layer_norm_for_extract""", ] def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" for attribute in key.split("." ): a__ : Optional[Any] =getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if weight_type is not None: a__ : Optional[Any] =getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).shape else: a__ : Optional[Any] =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__ : Optional[int] =value elif weight_type == "weight_g": a__ : List[str] =value elif weight_type == "weight_v": a__ : Any =value elif weight_type == "bias": a__ : Optional[int] =value else: a__ : int =value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Any ): """simple docstring""" a__ : int =[] a__ : Optional[Any] =fairseq_model.state_dict() a__ : Any =hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): a__ : List[str] =False if "conv_layers" in name: load_conv_layer( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == "group" , ) a__ : Any =True else: for key, mapped_key in MAPPING.items(): a__ : str ="unispeech_sat." + 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]: if "layer_norm_for_extract" in name and (".".join(name.split("." )[:-1] ) != key): # special case since naming is very similar continue a__ : Tuple =True if "*" in mapped_key: a__ : Union[str, Any] =name.split(SCREAMING_SNAKE_CASE )[0].split("." )[-2] a__ : Any =mapped_key.replace("*" , SCREAMING_SNAKE_CASE ) if "weight_g" in name: a__ : Any ="weight_g" elif "weight_v" in name: a__ : Union[str, Any] ="weight_v" elif "bias" in name: a__ : Tuple ="bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj a__ : int ="weight" else: a__ : Optional[Any] =None set_recursively(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _A ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" a__ : Optional[Any] =full_name.split("conv_layers." )[-1] a__ : Dict =name.split("." ) a__ : str =int(items[0] ) a__ : Union[str, Any] =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__ : Optional[Any] =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[layer_id].layer_norm.bias.data.shape} was found.''' ) a__ : int =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[layer_id].layer_norm.weight.data.shape} was found.''' ) a__ : List[str] =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(SCREAMING_SNAKE_CASE ) @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : List[Any]=None , SCREAMING_SNAKE_CASE : Optional[int]=None , SCREAMING_SNAKE_CASE : Any=True ): """simple docstring""" if config_path is not None: a__ : Optional[int] =UniSpeechSatConfig.from_pretrained(SCREAMING_SNAKE_CASE ) else: a__ : Optional[Any] =UniSpeechSatConfig() a__ : List[Any] ="" if is_finetuned: a__ : Optional[int] =UniSpeechSatForCTC(SCREAMING_SNAKE_CASE ) else: a__ : int =UniSpeechSatForPreTraining(SCREAMING_SNAKE_CASE ) a__ , a__ , a__ : str =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) a__ : Optional[Any] =model[0].eval() recursively_load_weights(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) hf_wavavec.save_pretrained(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = 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""" ) UpperCAmelCase : Union[str, Any] = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
95
import numpy as np def _A ( SCREAMING_SNAKE_CASE : np.array ): """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
95
1
import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def _A ( SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" return EnvironmentCommand() def _A ( SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" return EnvironmentCommand(args.accelerate_config_file ) class __lowerCAmelCase ( UpperCamelCase__): @staticmethod def _lowercase ( lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : Tuple =parser.add_parser("env" ) download_parser.set_defaults(func=lowerCAmelCase__ ) download_parser.add_argument( "--accelerate-config_file" , default=lowerCAmelCase__ , help="The accelerate config file to use for the default values in the launching script." , ) download_parser.set_defaults(func=lowerCAmelCase__ ) def __init__( self , lowerCAmelCase__ , *lowerCAmelCase__ ) -> None: '''simple docstring''' a__ : Optional[Any] =accelerate_config_file def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : List[str] ="not installed" if is_safetensors_available(): import safetensors a__ : Tuple =safetensors.__version__ elif importlib.util.find_spec("safetensors" ) is not None: import safetensors a__ : Tuple =F'''{safetensors.__version__} but is ignored because of PyTorch version too old.''' a__ : Union[str, Any] ="not installed" a__ : Union[str, Any] ="not found" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file a__ : List[str] =accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(lowerCAmelCase__ ): a__ : int =load_config_from_file(self._accelerate_config_file ).to_dict() a__ : Union[str, Any] =( "\n".join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else F'''\t{accelerate_config}''' ) a__ : Tuple ="not installed" a__ : List[str] ="NA" if is_torch_available(): import torch a__ : List[Any] =torch.__version__ a__ : Tuple =torch.cuda.is_available() a__ : Optional[Any] ="not installed" a__ : Optional[int] ="NA" if is_tf_available(): import tensorflow as tf a__ : List[str] =tf.__version__ try: # deprecated in v2.1 a__ : List[str] =tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool a__ : Optional[Any] =bool(tf.config.list_physical_devices("GPU" ) ) a__ : Optional[Any] ="not installed" a__ : Union[str, Any] ="not installed" a__ : Optional[int] ="not installed" a__ : Optional[int] ="NA" if is_flax_available(): import flax import jax import jaxlib a__ : int =flax.__version__ a__ : Dict =jax.__version__ a__ : str =jaxlib.__version__ a__ : List[str] =jax.lib.xla_bridge.get_backend().platform a__ : Any ={ "`transformers` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Huggingface_hub version": huggingface_hub.__version__, "Safetensors version": F'''{safetensors_version}''', "Accelerate version": F'''{accelerate_version}''', "Accelerate config": F'''{accelerate_config_str}''', "PyTorch version (GPU?)": F'''{pt_version} ({pt_cuda_available})''', "Tensorflow version (GPU?)": F'''{tf_version} ({tf_cuda_available})''', "Flax version (CPU?/GPU?/TPU?)": F'''{flax_version} ({jax_backend})''', "Jax version": F'''{jax_version}''', "JaxLib version": F'''{jaxlib_version}''', "Using GPU in script?": "<fill in>", "Using distributed or parallel set-up in script?": "<fill in>", } print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" ) print(self.format_dict(lowerCAmelCase__ ) ) return info @staticmethod def _lowercase ( lowerCAmelCase__ ) -> str: '''simple docstring''' return "\n".join([F'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
95
import numpy # List of input, output pairs UpperCAmelCase : str = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) UpperCAmelCase : Optional[int] = (((515, 22, 13), 555), ((61, 35, 49), 150)) UpperCAmelCase : str = [2, 4, 1, 5] UpperCAmelCase : List[str] = len(train_data) UpperCAmelCase : Dict = 0.0_0_9 def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Tuple="train" ): """simple docstring""" return calculate_hypothesis_value(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) - output( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : Tuple =0 for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : int=m ): """simple docstring""" a__ : Any =0 for i in range(SCREAMING_SNAKE_CASE ): if index == -1: summation_value += _error(SCREAMING_SNAKE_CASE ) else: summation_value += _error(SCREAMING_SNAKE_CASE ) * train_data[i][0][index] return summation_value def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Any =summation_of_cost_derivative(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) / m return cost_derivative_value def _A ( ): """simple docstring""" global parameter_vector # Tune these values to set a tolerance value for predicted output a__ : Dict =0.0_0_0_0_0_2 a__ : Union[str, Any] =0 a__ : Any =0 while True: j += 1 a__ : Any =[0, 0, 0, 0] for i in range(0 , len(SCREAMING_SNAKE_CASE ) ): a__ : Tuple =get_cost_derivative(i - 1 ) a__ : List[Any] =( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE , rtol=SCREAMING_SNAKE_CASE , ): break a__ : Optional[Any] =temp_parameter_vector print(("Number of iterations:", j) ) def _A ( ): """simple docstring""" for i in range(len(SCREAMING_SNAKE_CASE ) ): print(("Actual output value:", output(SCREAMING_SNAKE_CASE , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(SCREAMING_SNAKE_CASE , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("""\nTesting gradient descent for a linear hypothesis function.\n""") test_gradient_descent()
95
1
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel 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 enable_full_determinism() class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Any =1 a__ : Dict =3 a__ : List[str] =(3_2, 3_2) a__ : Any =floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowerCAmelCase__ ) return image @property def _lowercase ( self ) -> str: '''simple docstring''' torch.manual_seed(0 ) a__ : int =UNetaDConditionModel( block_out_channels=(3_2, 3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=7 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=3_2 , attention_head_dim=8 , use_linear_projection=lowerCAmelCase__ , only_cross_attention=(True, True, False) , num_class_embeds=1_0_0 , ) return model @property def _lowercase ( self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) a__ : Optional[Any] =AutoencoderKL( block_out_channels=[3_2, 3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def _lowercase ( self ) -> Tuple: '''simple docstring''' torch.manual_seed(0 ) a__ : Any =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , 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 , hidden_act="gelu" , projection_dim=5_1_2 , ) return CLIPTextModel(lowerCAmelCase__ ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] ="cpu" # ensure determinism for the device-dependent torch.Generator a__ : Union[str, Any] =self.dummy_cond_unet_upscale a__ : Union[str, Any] =DDPMScheduler() a__ : Optional[Any] =DDIMScheduler(prediction_type="v_prediction" ) a__ : List[Any] =self.dummy_vae a__ : List[Any] =self.dummy_text_encoder a__ : Any =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) a__ : int =self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] a__ : Dict =Image.fromarray(np.uinta(lowerCAmelCase__ ) ).convert("RGB" ).resize((6_4, 6_4) ) # make sure here that pndm scheduler skips prk a__ : Optional[Any] =StableDiffusionUpscalePipeline( unet=lowerCAmelCase__ , low_res_scheduler=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , vae=lowerCAmelCase__ , text_encoder=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , max_noise_level=3_5_0 , ) a__ : Any =sd_pipe.to(lowerCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : str ="A painting of a squirrel eating a burger" a__ : Optional[Any] =torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 ) a__ : Optional[int] =sd_pipe( [prompt] , image=lowerCAmelCase__ , generator=lowerCAmelCase__ , guidance_scale=6.0 , noise_level=2_0 , num_inference_steps=2 , output_type="np" , ) a__ : Any =output.images a__ : str =torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 ) a__ : Any =sd_pipe( [prompt] , image=lowerCAmelCase__ , generator=lowerCAmelCase__ , guidance_scale=6.0 , noise_level=2_0 , num_inference_steps=2 , output_type="np" , return_dict=lowerCAmelCase__ , )[0] a__ : str =image[0, -3:, -3:, -1] a__ : Tuple =image_from_tuple[0, -3:, -3:, -1] a__ : str =low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) a__ : Optional[int] =np.array([0.31_13, 0.39_10, 0.42_72, 0.48_59, 0.50_61, 0.46_52, 0.53_62, 0.57_15, 0.56_61] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : List[str] ="cpu" # ensure determinism for the device-dependent torch.Generator a__ : Optional[Any] =self.dummy_cond_unet_upscale a__ : str =DDPMScheduler() a__ : Union[str, Any] =DDIMScheduler(prediction_type="v_prediction" ) a__ : Optional[int] =self.dummy_vae a__ : Any =self.dummy_text_encoder a__ : Union[str, Any] =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) a__ : Optional[Any] =self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] a__ : Any =Image.fromarray(np.uinta(lowerCAmelCase__ ) ).convert("RGB" ).resize((6_4, 6_4) ) # make sure here that pndm scheduler skips prk a__ : List[Any] =StableDiffusionUpscalePipeline( unet=lowerCAmelCase__ , low_res_scheduler=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , vae=lowerCAmelCase__ , text_encoder=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , max_noise_level=3_5_0 , ) a__ : Any =sd_pipe.to(lowerCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Dict ="A painting of a squirrel eating a burger" a__ : int =sd_pipe( 2 * [prompt] , image=2 * [low_res_image] , guidance_scale=6.0 , noise_level=2_0 , num_inference_steps=2 , output_type="np" , ) a__ : str =output.images assert image.shape[0] == 2 a__ : Tuple =torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 ) a__ : int =sd_pipe( [prompt] , image=lowerCAmelCase__ , generator=lowerCAmelCase__ , num_images_per_prompt=2 , guidance_scale=6.0 , noise_level=2_0 , num_inference_steps=2 , output_type="np" , ) a__ : Optional[int] =output.images assert image.shape[0] == 2 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =self.dummy_cond_unet_upscale a__ : Tuple =DDPMScheduler() a__ : Dict =DDIMScheduler(prediction_type="v_prediction" ) a__ : Optional[int] =self.dummy_vae a__ : str =self.dummy_text_encoder a__ : Optional[int] =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) a__ : Dict =self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] a__ : int =Image.fromarray(np.uinta(lowerCAmelCase__ ) ).convert("RGB" ).resize((6_4, 6_4) ) # put models in fp16, except vae as it overflows in fp16 a__ : Any =unet.half() a__ : int =text_encoder.half() # make sure here that pndm scheduler skips prk a__ : List[Any] =StableDiffusionUpscalePipeline( unet=lowerCAmelCase__ , low_res_scheduler=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , vae=lowerCAmelCase__ , text_encoder=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , max_noise_level=3_5_0 , ) a__ : int =sd_pipe.to(lowerCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Dict ="A painting of a squirrel eating a burger" a__ : str =torch.manual_seed(0 ) a__ : Optional[Any] =sd_pipe( [prompt] , image=lowerCAmelCase__ , generator=lowerCAmelCase__ , num_inference_steps=2 , output_type="np" , ).images a__ : List[str] =low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) @slow @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self ) -> str: '''simple docstring''' a__ : List[Any] =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-upscale/low_res_cat.png" ) a__ : Optional[int] =load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale" "/upsampled_cat.npy" ) a__ : Optional[int] ="stabilityai/stable-diffusion-x4-upscaler" a__ : str =StableDiffusionUpscalePipeline.from_pretrained(lowerCAmelCase__ ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing() a__ : Union[str, Any] ="a cat sitting on a park bench" a__ : Optional[Any] =torch.manual_seed(0 ) a__ : List[Any] =pipe( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , generator=lowerCAmelCase__ , output_type="np" , ) a__ : int =output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 1E-3 def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Union[str, Any] =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-upscale/low_res_cat.png" ) a__ : int =load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale" "/upsampled_cat_fp16.npy" ) a__ : Union[str, Any] ="stabilityai/stable-diffusion-x4-upscaler" a__ : List[str] =StableDiffusionUpscalePipeline.from_pretrained( lowerCAmelCase__ , torch_dtype=torch.floataa , ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing() a__ : Any ="a cat sitting on a park bench" a__ : Any =torch.manual_seed(0 ) a__ : Any =pipe( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , generator=lowerCAmelCase__ , output_type="np" , ) a__ : Dict =output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _lowercase ( self ) -> List[str]: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() a__ : List[Any] =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-upscale/low_res_cat.png" ) a__ : int ="stabilityai/stable-diffusion-x4-upscaler" a__ : Union[str, Any] =StableDiffusionUpscalePipeline.from_pretrained( lowerCAmelCase__ , torch_dtype=torch.floataa , ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() a__ : str ="a cat sitting on a park bench" a__ : Union[str, Any] =torch.manual_seed(0 ) a__ : Optional[int] =pipe( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , generator=lowerCAmelCase__ , num_inference_steps=5 , output_type="np" , ) a__ : Optional[int] =torch.cuda.max_memory_allocated() # make sure that less than 2.9 GB is allocated assert mem_bytes < 2.9 * 1_0**9
95
def _A ( SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" a__ : Optional[Any] =len(SCREAMING_SNAKE_CASE ) while cur > 1: # Find the maximum number in arr a__ : List[Any] =arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi a__ : int =arr[mi::-1] + arr[mi + 1 : len(SCREAMING_SNAKE_CASE )] # Reverse whole list a__ : List[str] =arr[cur - 1 :: -1] + arr[cur : len(SCREAMING_SNAKE_CASE )] cur -= 1 return arr if __name__ == "__main__": UpperCAmelCase : int = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase : Optional[int] = [int(item) for item in user_input.split(""",""")] print(pancake_sort(unsorted))
95
1
import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch UpperCAmelCase : List[str] = True except ImportError: UpperCAmelCase : Optional[Any] = False try: from torch.hub import _get_torch_home UpperCAmelCase : Optional[int] = _get_torch_home() except ImportError: UpperCAmelCase : Optional[Any] = os.path.expanduser( os.getenv("""TORCH_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """torch""")) ) UpperCAmelCase : Union[str, Any] = os.path.join(torch_cache_home, """transformers""") UpperCAmelCase : Optional[Any] = """https://cdn.huggingface.co""" UpperCAmelCase : int = """https://s3.amazonaws.com/models.huggingface.co/bert""" UpperCAmelCase : Optional[int] = """/""".join(str(Path(__file__).resolve()).split("""/""")[:-1]) UpperCAmelCase : Union[str, Any] = os.path.join(PATH, """config.yaml""") UpperCAmelCase : str = os.path.join(PATH, """attributes.txt""") UpperCAmelCase : int = os.path.join(PATH, """objects.txt""") UpperCAmelCase : int = os.getenv("""PYTORCH_PRETRAINED_BERT_CACHE""", default_cache_path) UpperCAmelCase : List[str] = os.getenv("""PYTORCH_TRANSFORMERS_CACHE""", PYTORCH_PRETRAINED_BERT_CACHE) UpperCAmelCase : Dict = os.getenv("""TRANSFORMERS_CACHE""", PYTORCH_TRANSFORMERS_CACHE) UpperCAmelCase : Union[str, Any] = """pytorch_model.bin""" UpperCAmelCase : List[Any] = """config.yaml""" def _A ( SCREAMING_SNAKE_CASE : Tuple=OBJECTS , SCREAMING_SNAKE_CASE : Dict=ATTRIBUTES ): """simple docstring""" a__ : List[str] =[] with open(SCREAMING_SNAKE_CASE ) as f: for object in f.readlines(): vg_classes.append(object.split("," )[0].lower().strip() ) a__ : Optional[Any] =[] with open(SCREAMING_SNAKE_CASE ) as f: for object in f.readlines(): vg_attrs.append(object.split("," )[0].lower().strip() ) return vg_classes, vg_attrs def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" a__ : Union[str, Any] =OrderedDict() with open(SCREAMING_SNAKE_CASE , "rb" ) as f: a__ : List[Any] =pkl.load(SCREAMING_SNAKE_CASE )["model"] for k in copy.deepcopy(list(ckp.keys() ) ): a__ : Optional[int] =ckp.pop(SCREAMING_SNAKE_CASE ) if isinstance(SCREAMING_SNAKE_CASE , np.ndarray ): a__ : int =torch.tensor(SCREAMING_SNAKE_CASE ) else: assert isinstance(SCREAMING_SNAKE_CASE , torch.tensor ), type(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =v return r class __lowerCAmelCase : _lowercase : List[Any] = {} def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = "root" , lowerCAmelCase__=0 ) -> Tuple: '''simple docstring''' a__ : Optional[Any] =name a__ : Optional[Any] =level a__ : Optional[Any] ={} for k, v in dictionary.items(): if v is None: raise ValueError() a__ : int =copy.deepcopy(lowerCAmelCase__ ) a__ : Optional[int] =copy.deepcopy(lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Dict =Config(lowerCAmelCase__ , name=lowerCAmelCase__ , level=level + 1 ) a__ : int =v setattr(self , lowerCAmelCase__ , lowerCAmelCase__ ) a__ : int =d def __repr__( self ) -> List[Any]: '''simple docstring''' return str(list((self._pointer.keys()) ) ) def __setattr__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> str: '''simple docstring''' a__ : List[str] =val a__ : Dict =val a__ : int =key.split("." ) a__ : Optional[Any] =len(lowerCAmelCase__ ) - 1 a__ : str =self._pointer if len(lowerCAmelCase__ ) > 1: for i, l in enumerate(lowerCAmelCase__ ): if hasattr(self , lowerCAmelCase__ ) and isinstance(getattr(self , lowerCAmelCase__ ) , lowerCAmelCase__ ): setattr(getattr(self , lowerCAmelCase__ ) , ".".join(levels[i:] ) , lowerCAmelCase__ ) if l == last_level: a__ : str =val else: a__ : Union[str, Any] =pointer[l] def _lowercase ( self ) -> int: '''simple docstring''' return self._pointer def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' with open(F'''{file_name}''' , "w" ) as stream: dump(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: '''simple docstring''' with open(F'''{file_name}''' , "w" ) as stream: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) @staticmethod def _lowercase ( lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' with open(lowerCAmelCase__ ) as stream: a__ : Tuple =load(lowerCAmelCase__ , Loader=lowerCAmelCase__ ) return data def __str__( self ) -> Tuple: '''simple docstring''' a__ : str =" " if self._name != "root": a__ : Optional[int] =F'''{t * (self._level-1)}{self._name}:\n''' else: a__ : Union[str, Any] ="" a__ : List[str] =self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): r += F'''{t * (self._level)}{v}\n''' self._level += 1 else: r += F'''{t * (self._level)}{k}: {v} ({type(lowerCAmelCase__ ).__name__})\n''' a__ : Optional[int] =level return r[:-1] @classmethod def _lowercase ( cls , lowerCAmelCase__ , **lowerCAmelCase__ ) -> int: '''simple docstring''' a__ , a__ : Dict =cls.get_config_dict(lowerCAmelCase__ , **lowerCAmelCase__ ) return cls(lowerCAmelCase__ ) @classmethod def _lowercase ( cls , lowerCAmelCase__ , **lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] =kwargs.pop("cache_dir" , lowerCAmelCase__ ) a__ : List[str] =kwargs.pop("force_download" , lowerCAmelCase__ ) a__ : int =kwargs.pop("resume_download" , lowerCAmelCase__ ) a__ : Optional[Any] =kwargs.pop("proxies" , lowerCAmelCase__ ) a__ : Any =kwargs.pop("local_files_only" , lowerCAmelCase__ ) if os.path.isdir(lowerCAmelCase__ ): a__ : Any =os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) elif os.path.isfile(lowerCAmelCase__ ) or is_remote_url(lowerCAmelCase__ ): a__ : Dict =pretrained_model_name_or_path else: a__ : int =hf_bucket_url(lowerCAmelCase__ , filename=lowerCAmelCase__ , use_cdn=lowerCAmelCase__ ) try: # Load from URL or cache if already cached a__ : Optional[Any] =cached_path( lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , force_download=lowerCAmelCase__ , proxies=lowerCAmelCase__ , resume_download=lowerCAmelCase__ , local_files_only=lowerCAmelCase__ , ) # Load config dict if resolved_config_file is None: raise EnvironmentError a__ : Tuple =Config.load_yaml(lowerCAmelCase__ ) except EnvironmentError: a__ : Union[str, Any] ="Can't load config for" raise EnvironmentError(lowerCAmelCase__ ) if resolved_config_file == config_file: print("loading configuration file from path" ) else: print("loading configuration file cache" ) return Config.load_yaml(lowerCAmelCase__ ), kwargs def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" a__ : List[Any] =torch.load("dump.pt" , map_location=in_tensor.device ) a__ : Any =in_tensor.numpy() a__ : Any =out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , rtol=0.0_1 , atol=0.1 ), ( f'''{sum([1 for x in np.isclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , rtol=0.0_1 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %''' " element-wise mismatch" ) raise Exception("tensors are all good" ) # Hugging face functions below def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" a__ : Dict =urlparse(SCREAMING_SNAKE_CASE ) return parsed.scheme in ("http", "https") def _A ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : List[str]=True ): """simple docstring""" a__ : Optional[int] =CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX a__ : int ="/" not in model_id if legacy_format: return f'''{endpoint}/{model_id}-{filename}''' else: return f'''{endpoint}/{model_id}/{filename}''' def _A ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int]=None , SCREAMING_SNAKE_CASE : str=0 , SCREAMING_SNAKE_CASE : List[str]=None , ): """simple docstring""" a__ : List[str] ="python/{}".format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): ua += "; " + "; ".join("{}/{}".format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for k, v in user_agent.items() ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): ua += "; " + user_agent a__ : List[str] ={"user-agent": ua} if resume_size > 0: a__ : str ="bytes=%d-" % (resume_size,) a__ : int =requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE , proxies=SCREAMING_SNAKE_CASE , headers=SCREAMING_SNAKE_CASE ) if response.status_code == 416: # Range not satisfiable return a__ : Optional[int] =response.headers.get("Content-Length" ) a__ : Dict =resume_size + int(SCREAMING_SNAKE_CASE ) if content_length is not None else None a__ : Any =tqdm( unit="B" , unit_scale=SCREAMING_SNAKE_CASE , total=SCREAMING_SNAKE_CASE , initial=SCREAMING_SNAKE_CASE , desc="Downloading" , ) for chunk in response.iter_content(chunk_size=1_024 ): if chunk: # filter out keep-alive new chunks progress.update(len(SCREAMING_SNAKE_CASE ) ) temp_file.write(SCREAMING_SNAKE_CASE ) progress.close() def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Optional[int]=None , SCREAMING_SNAKE_CASE : Dict=False , SCREAMING_SNAKE_CASE : List[Any]=None , SCREAMING_SNAKE_CASE : Optional[int]=10 , SCREAMING_SNAKE_CASE : List[str]=False , SCREAMING_SNAKE_CASE : Optional[Any]=None , SCREAMING_SNAKE_CASE : List[Any]=False , ): """simple docstring""" if cache_dir is None: a__ : int =TRANSFORMERS_CACHE if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): a__ : Tuple =str(SCREAMING_SNAKE_CASE ) os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) a__ : List[Any] =None if not local_files_only: try: a__ : Union[str, Any] =requests.head(SCREAMING_SNAKE_CASE , allow_redirects=SCREAMING_SNAKE_CASE , proxies=SCREAMING_SNAKE_CASE , timeout=SCREAMING_SNAKE_CASE ) if response.status_code == 200: a__ : Tuple =response.headers.get("ETag" ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass a__ : List[Any] =url_to_filename(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # get cache path to put the file a__ : str =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(SCREAMING_SNAKE_CASE ): return cache_path else: a__ : Dict =[ file for file in fnmatch.filter(os.listdir(SCREAMING_SNAKE_CASE ) , filename + ".*" ) if not file.endswith(".json" ) and not file.endswith(".lock" ) ] if len(SCREAMING_SNAKE_CASE ) > 0: return os.path.join(SCREAMING_SNAKE_CASE , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( "Cannot find the requested files in the cached path and outgoing traffic has been" " disabled. To enable model look-ups and downloads online, set 'local_files_only'" " to False." ) return None # From now on, etag is not None. if os.path.exists(SCREAMING_SNAKE_CASE ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. a__ : Dict =cache_path + ".lock" with FileLock(SCREAMING_SNAKE_CASE ): # If the download just completed while the lock was activated. if os.path.exists(SCREAMING_SNAKE_CASE ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: a__ : Any =cache_path + ".incomplete" @contextmanager def _resumable_file_manager(): with open(SCREAMING_SNAKE_CASE , "a+b" ) as f: yield f a__ : Optional[int] =_resumable_file_manager if os.path.exists(SCREAMING_SNAKE_CASE ): a__ : Dict =os.stat(SCREAMING_SNAKE_CASE ).st_size else: a__ : Dict =0 else: a__ : Dict =partial(tempfile.NamedTemporaryFile , dir=SCREAMING_SNAKE_CASE , delete=SCREAMING_SNAKE_CASE ) a__ : Union[str, Any] =0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( "%s not found in cache or force_download set to True, downloading to %s" , SCREAMING_SNAKE_CASE , temp_file.name , ) http_get( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , proxies=SCREAMING_SNAKE_CASE , resume_size=SCREAMING_SNAKE_CASE , user_agent=SCREAMING_SNAKE_CASE , ) os.replace(temp_file.name , SCREAMING_SNAKE_CASE ) a__ : str ={"url": url, "etag": etag} a__ : List[Any] =cache_path + ".json" with open(SCREAMING_SNAKE_CASE , "w" ) as meta_file: json.dump(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return cache_path def _A ( SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Dict=None ): """simple docstring""" a__ : Dict =url.encode("utf-8" ) a__ : Dict =shaaaa(SCREAMING_SNAKE_CASE ) a__ : int =url_hash.hexdigest() if etag: a__ : Optional[int] =etag.encode("utf-8" ) a__ : List[str] =shaaaa(SCREAMING_SNAKE_CASE ) filename += "." + etag_hash.hexdigest() if url.endswith(".h5" ): filename += ".h5" return filename def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[Any]=None , SCREAMING_SNAKE_CASE : str=False , SCREAMING_SNAKE_CASE : Any=None , SCREAMING_SNAKE_CASE : Dict=False , SCREAMING_SNAKE_CASE : List[Any]=None , SCREAMING_SNAKE_CASE : Optional[int]=False , SCREAMING_SNAKE_CASE : Any=False , SCREAMING_SNAKE_CASE : Optional[int]=False , ): """simple docstring""" if cache_dir is None: a__ : Union[str, Any] =TRANSFORMERS_CACHE if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): a__ : int =str(SCREAMING_SNAKE_CASE ) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): a__ : Dict =str(SCREAMING_SNAKE_CASE ) if is_remote_url(SCREAMING_SNAKE_CASE ): # URL, so get it from the cache (downloading if necessary) a__ : List[Any] =get_from_cache( SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE , force_download=SCREAMING_SNAKE_CASE , proxies=SCREAMING_SNAKE_CASE , resume_download=SCREAMING_SNAKE_CASE , user_agent=SCREAMING_SNAKE_CASE , local_files_only=SCREAMING_SNAKE_CASE , ) elif os.path.exists(SCREAMING_SNAKE_CASE ): # File, and it exists. a__ : Tuple =url_or_filename elif urlparse(SCREAMING_SNAKE_CASE ).scheme == "": # File, but it doesn't exist. raise EnvironmentError("file {} not found".format(SCREAMING_SNAKE_CASE ) ) else: # Something unknown raise ValueError("unable to parse {} as a URL or as a local path".format(SCREAMING_SNAKE_CASE ) ) if extract_compressed_file: if not is_zipfile(SCREAMING_SNAKE_CASE ) and not tarfile.is_tarfile(SCREAMING_SNAKE_CASE ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" a__ , a__ : List[Any] =os.path.split(SCREAMING_SNAKE_CASE ) a__ : int =output_file.replace("." , "-" ) + "-extracted" a__ : str =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if os.path.isdir(SCREAMING_SNAKE_CASE ) and os.listdir(SCREAMING_SNAKE_CASE ) and not force_extract: return output_path_extracted # Prevent parallel extractions a__ : List[Any] =output_path + ".lock" with FileLock(SCREAMING_SNAKE_CASE ): shutil.rmtree(SCREAMING_SNAKE_CASE , ignore_errors=SCREAMING_SNAKE_CASE ) os.makedirs(SCREAMING_SNAKE_CASE ) if is_zipfile(SCREAMING_SNAKE_CASE ): with ZipFile(SCREAMING_SNAKE_CASE , "r" ) as zip_file: zip_file.extractall(SCREAMING_SNAKE_CASE ) zip_file.close() elif tarfile.is_tarfile(SCREAMING_SNAKE_CASE ): a__ : Optional[Any] =tarfile.open(SCREAMING_SNAKE_CASE ) tar_file.extractall(SCREAMING_SNAKE_CASE ) tar_file.close() else: raise EnvironmentError("Archive format of {} could not be identified".format(SCREAMING_SNAKE_CASE ) ) return output_path_extracted return output_path def _A ( SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Union[str, Any]="," ): """simple docstring""" assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if os.path.isfile(SCREAMING_SNAKE_CASE ): with open(SCREAMING_SNAKE_CASE ) as f: a__ : str =eval(f.read() ) else: a__ : Tuple =requests.get(SCREAMING_SNAKE_CASE ) try: a__ : List[Any] =requests.json() except Exception: a__ : Optional[Any] =req.content.decode() assert data is not None, "could not connect" try: a__ : List[Any] =eval(SCREAMING_SNAKE_CASE ) except Exception: a__ : int =data.split("\n" ) req.close() return data def _A ( SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" a__ : Optional[int] =requests.get(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =np.array(Image.open(BytesIO(response.content ) ) ) return img def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Optional[Any] =url.split("/" )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(SCREAMING_SNAKE_CASE ) with open(SCREAMING_SNAKE_CASE , "rb" ) as stream: a__ : Dict =pkl.load(SCREAMING_SNAKE_CASE ) a__ : List[str] =weights.pop("model" ) a__ : Union[str, Any] ={} for k, v in model.items(): a__ : Optional[int] =torch.from_numpy(SCREAMING_SNAKE_CASE ) if "running_var" in k: a__ : str =torch.tensor([0] ) a__ : Optional[Any] =k.replace("running_var" , "num_batches_tracked" ) a__ : int =zero return new def _A ( ): """simple docstring""" print(f'''{os.path.abspath(os.path.join(SCREAMING_SNAKE_CASE , os.pardir ) )}/demo.ipynb''' ) def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : List[Any]="RGB" ): """simple docstring""" assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if os.path.isfile(SCREAMING_SNAKE_CASE ): a__ : Optional[Any] =cva.imread(SCREAMING_SNAKE_CASE ) else: a__ : Union[str, Any] =get_image_from_url(SCREAMING_SNAKE_CASE ) assert img is not None, f'''could not connect to: {im}''' a__ : Optional[Any] =cva.cvtColor(SCREAMING_SNAKE_CASE , cva.COLOR_BGR2RGB ) if input_format == "RGB": a__ : str =img[:, :, ::-1] return img def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Union[str, Any]=1 ): """simple docstring""" return (images[i : i + batch] for i in range(0 , len(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ))
95
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Any =tempfile.mkdtemp() # fmt: off a__ : List[Any] =["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on a__ : str =dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) a__ : List[Any] =["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""] a__ : Optional[int] ={"unk_token": "<unk>"} a__ : Optional[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) a__ : Tuple =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowerCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(lowerCAmelCase__ ) ) a__ : Optional[Any] ={ "do_resize": True, "size": 2_0, "do_center_crop": True, "crop_size": 1_8, "do_normalize": True, "image_mean": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], "image_std": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } a__ : Dict =os.path.join(self.tmpdirname , lowerCAmelCase__ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Any: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =[np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] a__ : List[Any] =[Image.fromarray(np.moveaxis(lowerCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Union[str, Any] =self.get_tokenizer() a__ : int =self.get_rust_tokenizer() a__ : List[str] =self.get_image_processor() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) a__ : Optional[Any] =CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=lowerCAmelCase__ ) a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) a__ : Dict =CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor , lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a__ : str =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) a__ : int =self.get_image_processor(do_normalize=lowerCAmelCase__ , padding_value=1.0 ) a__ : Optional[Any] =CLIPSegProcessor.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 _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : str =self.get_image_processor() a__ : Optional[int] =self.get_tokenizer() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : str =self.prepare_image_inputs() a__ : Any =image_processor(lowerCAmelCase__ , return_tensors="np" ) a__ : Optional[int] =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 _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : List[Any] =self.get_tokenizer() a__ : Optional[int] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Union[str, Any] ="lower newer" a__ : List[str] =processor(text=lowerCAmelCase__ ) a__ : str =tokenizer(lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =self.get_image_processor() a__ : Dict =self.get_tokenizer() a__ : Union[str, Any] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict ="lower newer" a__ : int =self.prepare_image_inputs() a__ : Any =processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> str: '''simple docstring''' a__ : Union[str, Any] =self.get_image_processor() a__ : Optional[Any] =self.get_tokenizer() a__ : str =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : int =self.prepare_image_inputs() a__ : Union[str, Any] =self.prepare_image_inputs() a__ : Tuple =processor(images=lowerCAmelCase__ , visual_prompt=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "conditional_pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : Any =self.get_tokenizer() a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a__ : Optional[Any] =processor.batch_decode(lowerCAmelCase__ ) a__ : Dict =tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
95
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Tuple = { """configuration_xmod""": [ """XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XmodConfig""", """XmodOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict = [ """XMOD_PRETRAINED_MODEL_ARCHIVE_LIST""", """XmodForCausalLM""", """XmodForMaskedLM""", """XmodForMultipleChoice""", """XmodForQuestionAnswering""", """XmodForSequenceClassification""", """XmodForTokenClassification""", """XmodModel""", """XmodPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
95
def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) if len(SCREAMING_SNAKE_CASE ) == 1: return True a__ : Union[str, Any] =series[1] - series[0] for index in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) a__ : Any =0 for val in series: answer += val return answer / len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
95
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer UpperCAmelCase : Optional[Any] = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase : Union[str, Any] = { """vocab_file""": { """google/electra-small-generator""": ( """https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt""" ), """google/electra-base-generator""": """https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt""", """google/electra-large-generator""": ( """https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt""" ), """google/electra-small-discriminator""": ( """https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt""" ), """google/electra-base-discriminator""": ( """https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt""" ), """google/electra-large-discriminator""": ( """https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """google/electra-small-generator""": ( """https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json""" ), """google/electra-base-generator""": ( """https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json""" ), """google/electra-large-generator""": ( """https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json""" ), """google/electra-small-discriminator""": ( """https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json""" ), """google/electra-base-discriminator""": ( """https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json""" ), """google/electra-large-discriminator""": ( """https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json""" ), }, } UpperCAmelCase : List[str] = { """google/electra-small-generator""": 512, """google/electra-base-generator""": 512, """google/electra-large-generator""": 512, """google/electra-small-discriminator""": 512, """google/electra-base-discriminator""": 512, """google/electra-large-discriminator""": 512, } UpperCAmelCase : Tuple = { """google/electra-small-generator""": {"""do_lower_case""": True}, """google/electra-base-generator""": {"""do_lower_case""": True}, """google/electra-large-generator""": {"""do_lower_case""": True}, """google/electra-small-discriminator""": {"""do_lower_case""": True}, """google/electra-base-discriminator""": {"""do_lower_case""": True}, """google/electra-large-discriminator""": {"""do_lower_case""": True}, } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[str] = VOCAB_FILES_NAMES _lowercase : List[str] = PRETRAINED_VOCAB_FILES_MAP _lowercase : Tuple = PRETRAINED_INIT_CONFIGURATION _lowercase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : List[Any] = ElectraTokenizer def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__="[UNK]" , lowerCAmelCase__="[SEP]" , lowerCAmelCase__="[PAD]" , lowerCAmelCase__="[CLS]" , lowerCAmelCase__="[MASK]" , lowerCAmelCase__=True , lowerCAmelCase__=None , **lowerCAmelCase__ , ) -> List[str]: '''simple docstring''' super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , tokenize_chinese_chars=lowerCAmelCase__ , strip_accents=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : Optional[int] =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowerCAmelCase__ ) != do_lower_case or normalizer_state.get("strip_accents" , lowerCAmelCase__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowerCAmelCase__ ) != tokenize_chinese_chars ): a__ : Tuple =getattr(lowerCAmelCase__ , normalizer_state.pop("type" ) ) a__ : List[Any] =do_lower_case a__ : Optional[int] =strip_accents a__ : str =tokenize_chinese_chars a__ : str =normalizer_class(**lowerCAmelCase__ ) a__ : List[Any] =do_lower_case def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> Tuple: '''simple docstring''' a__ : str =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: '''simple docstring''' a__ : List[Any] =[self.sep_token_id] a__ : Tuple =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: '''simple docstring''' a__ : List[Any] =self._tokenizer.model.save(lowerCAmelCase__ , name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ )
95
import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Tuple = """M-CLIP""" def __init__( self , lowerCAmelCase__=1_0_2_4 , lowerCAmelCase__=7_6_8 , **lowerCAmelCase__ ) -> Any: '''simple docstring''' a__ : int =transformerDimSize a__ : Dict =imageDimSize super().__init__(**lowerCAmelCase__ ) class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = MCLIPConfig def __init__( self , lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> List[str]: '''simple docstring''' super().__init__(lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Tuple =XLMRobertaModel(lowerCAmelCase__ ) a__ : List[str] =torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[Any] =self.transformer(input_ids=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ )[0] a__ : int =(embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(lowerCAmelCase__ ), embs
95
1
# 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 __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = """philschmid/bart-large-cnn-samsum""" _lowercase : List[Any] = ( """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.""" ) _lowercase : Any = """summarizer""" _lowercase : Any = AutoTokenizer _lowercase : str = AutoModelForSeqaSeqLM _lowercase : Optional[int] = ["""text"""] _lowercase : Optional[int] = ["""text"""] def _lowercase ( self , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' return self.pre_processor(lowerCAmelCase__ , return_tensors="pt" , truncation=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return self.model.generate(**lowerCAmelCase__ )[0] def _lowercase ( self , lowerCAmelCase__ ) -> Any: '''simple docstring''' return self.pre_processor.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ )
95
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 ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to properly calculate the metrics on the # validation dataset when in a distributed system, and builds off the # `nlp_example.py` script. # # 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 help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # 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 : Any = 16 UpperCAmelCase : str = 32 def _A ( SCREAMING_SNAKE_CASE : Accelerator , SCREAMING_SNAKE_CASE : int = 16 ): """simple docstring""" a__ : int =AutoTokenizer.from_pretrained("bert-base-cased" ) a__ : List[str] =load_dataset("glue" , "mrpc" ) def tokenize_function(SCREAMING_SNAKE_CASE : List[Any] ): # max_length=None => use the model max length (it's actually the default) a__ : int =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__ : Dict =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__ : Dict =tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(SCREAMING_SNAKE_CASE : str ): # On TPU it's best to pad everything to the same length or training will be very slow. a__ : Optional[Any] =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__ : str =16 elif accelerator.mixed_precision != "no": a__ : Union[str, Any] =8 else: a__ : List[str] =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__ : Any =DataLoader( tokenized_datasets["train"] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE ) a__ : int =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 : str = mocked_dataloaders # noqa: F811 def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : str ): """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , SCREAMING_SNAKE_CASE ) == "1": a__ : Tuple =2 # Initialize accelerator a__ : int =Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a__ : Optional[int] =config["lr"] a__ : Union[str, Any] =int(config["num_epochs"] ) a__ : Any =int(config["seed"] ) a__ : Dict =int(config["batch_size"] ) a__ : int =evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation a__ : int =1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: a__ : Dict =batch_size // MAX_GPU_BATCH_SIZE a__ : Tuple =MAX_GPU_BATCH_SIZE set_seed(SCREAMING_SNAKE_CASE ) a__ , a__ : Optional[int] =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__ : List[str] =model.to(accelerator.device ) # Instantiate optimizer a__ : List[Any] =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) // gradient_accumulation_steps , ) # 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__ : Optional[int] =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() 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 ) a__ : Dict =model(**SCREAMING_SNAKE_CASE ) a__ : List[Any] =outputs.loss a__ : List[str] =loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() a__ : Optional[Any] =0 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__ : Any =model(**SCREAMING_SNAKE_CASE ) a__ : str =outputs.logits.argmax(dim=-1 ) a__ , a__ : List[str] =accelerator.gather((predictions, batch["labels"]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(SCREAMING_SNAKE_CASE ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples a__ : Optional[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] a__ : Dict =references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=SCREAMING_SNAKE_CASE , references=SCREAMING_SNAKE_CASE , ) a__ : Tuple =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , SCREAMING_SNAKE_CASE ) def _A ( ): """simple docstring""" a__ : List[str] =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." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) a__ : str =parser.parse_args() a__ : Optional[int] ={"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
95
1
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 ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Any=False ): """simple docstring""" a__ : Optional[int] =[] 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''') ) # projection layer + position embeddings rename_keys.extend( [ ("cls_token", "vit.embeddings.cls_token"), ("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"), ("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"), ("pos_embed", "vit.embeddings.position_embeddings"), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" a__ : 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"), ] ) return rename_keys def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : List[Any]=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: a__ : Dict ="" else: a__ : Tuple ="vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) a__ : List[str] =state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) a__ : List[Any] =state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict a__ : int =in_proj_weight[ : config.hidden_size, : ] a__ : Optional[Any] =in_proj_bias[: config.hidden_size] a__ : str =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] a__ : int =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] a__ : str =in_proj_weight[ -config.hidden_size :, : ] a__ : int =in_proj_bias[-config.hidden_size :] def _A ( SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : Optional[int] =["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" a__ : int =dct.pop(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =val def _A ( ): """simple docstring""" a__ : List[Any] ="http://images.cocodataset.org/val2017/000000039769.jpg" a__ : Union[str, Any] =Image.open(requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Tuple=True ): """simple docstring""" a__ : Dict =ViTConfig() # patch_size if model_name[-1] == "8": a__ : Optional[Any] =8 # set labels if required if not base_model: a__ : Dict =1_000 a__ : Dict ="huggingface/label-files" a__ : Tuple ="imagenet-1k-id2label.json" a__ : int =json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type="dataset" ) , "r" ) ) a__ : Tuple ={int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} a__ : List[Any] =idalabel a__ : Optional[Any] ={v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: a__ : str =384 a__ : str =1_536 a__ : List[Any] =12 a__ : Dict =6 # load original model from torch hub a__ : int =torch.hub.load("facebookresearch/dino:main" , SCREAMING_SNAKE_CASE ) original_model.eval() # load state_dict of original model, remove and rename some keys a__ : List[Any] =original_model.state_dict() if base_model: remove_classification_head_(SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =create_rename_keys(SCREAMING_SNAKE_CASE , base_model=SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) read_in_q_k_v(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # load HuggingFace model if base_model: a__ : Optional[int] =ViTModel(SCREAMING_SNAKE_CASE , add_pooling_layer=SCREAMING_SNAKE_CASE ).eval() else: a__ : str =ViTForImageClassification(SCREAMING_SNAKE_CASE ).eval() model.load_state_dict(SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by ViTImageProcessor a__ : Optional[int] =ViTImageProcessor() a__ : Optional[int] =image_processor(images=prepare_img() , return_tensors="pt" ) a__ : List[str] =encoding["pixel_values"] a__ : str =model(SCREAMING_SNAKE_CASE ) if base_model: a__ : List[str] =original_model(SCREAMING_SNAKE_CASE ) assert torch.allclose(SCREAMING_SNAKE_CASE , outputs.last_hidden_state[:, 0, :] , atol=1e-1 ) else: a__ : Optional[int] =original_model(SCREAMING_SNAKE_CASE ) assert logits.shape == outputs.logits.shape assert torch.allclose(SCREAMING_SNAKE_CASE , outputs.logits , atol=1e-3 ) Path(SCREAMING_SNAKE_CASE ).mkdir(exist_ok=SCREAMING_SNAKE_CASE ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""dino_vitb16""", type=str, help="""Name of the model trained with DINO 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( """--base_model""", action="""store_true""", help="""Whether to only convert the base model (no projection head weights).""", ) parser.set_defaults(base_model=True) UpperCAmelCase : Tuple = parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
95
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 MobileViTImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] =size if size is not None else {"shortest_edge": 2_0} a__ : List[str] =crop_size if crop_size is not None else {"height": 1_8, "width": 1_8} a__ : Tuple =parent a__ : Union[str, Any] =batch_size a__ : List[str] =num_channels a__ : List[Any] =image_size a__ : str =min_resolution a__ : Optional[int] =max_resolution a__ : Tuple =do_resize a__ : Union[str, Any] =size a__ : List[Any] =do_center_crop a__ : List[str] =crop_size a__ : Optional[int] =do_flip_channel_order def _lowercase ( self ) -> Optional[int]: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : int = MobileViTImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : Tuple =MobileViTImageProcessingTester(self ) @property def _lowercase ( self ) -> List[str]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : str =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_flip_channel_order" ) ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : List[Any] =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 2_0} ) self.assertEqual(image_processor.crop_size , {"height": 1_8, "width": 1_8} ) a__ : Union[str, Any] =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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' pass def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : 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 a__ : List[Any] =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : List[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input a__ : 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 a__ : int =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : int =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input a__ : List[str] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a__ : List[str] =image_processing(lowerCAmelCase__ , 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"], ) , )
95
1
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _A ( SCREAMING_SNAKE_CASE : int = 3 ): """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise TypeError("number of qubits must be a integer." ) if number_of_qubits <= 0: raise ValueError("number of qubits must be > 0." ) if math.floor(SCREAMING_SNAKE_CASE ) != number_of_qubits: raise ValueError("number of qubits must be exact integer." ) if number_of_qubits > 10: raise ValueError("number of qubits too large to simulate(>10)." ) a__ : Optional[int] =QuantumRegister(SCREAMING_SNAKE_CASE , "qr" ) a__ : List[Any] =ClassicalRegister(SCREAMING_SNAKE_CASE , "cr" ) a__ : int =QuantumCircuit(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =number_of_qubits for i in range(SCREAMING_SNAKE_CASE ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(SCREAMING_SNAKE_CASE ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(SCREAMING_SNAKE_CASE , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # simulate with 10000 shots a__ : Optional[Any] =Aer.get_backend("qasm_simulator" ) a__ : List[str] =execute(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , shots=10_000 ) return job.result().get_counts(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
95
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 MobileNetVaImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=None , ) -> Optional[int]: '''simple docstring''' a__ : str =size if size is not None else {"shortest_edge": 2_0} a__ : Union[str, Any] =crop_size if crop_size is not None else {"height": 1_8, "width": 1_8} a__ : Tuple =parent a__ : Optional[int] =batch_size a__ : Any =num_channels a__ : List[str] =image_size a__ : Dict =min_resolution a__ : List[Any] =max_resolution a__ : Dict =do_resize a__ : Union[str, Any] =size a__ : str =do_center_crop a__ : List[str] =crop_size def _lowercase ( self ) -> str: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : Optional[Any] = MobileNetVaImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =MobileNetVaImageProcessingTester(self ) @property def _lowercase ( self ) -> List[str]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "crop_size" ) ) def _lowercase ( self ) -> str: '''simple docstring''' a__ : Any =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 2_0} ) self.assertEqual(image_processor.crop_size , {"height": 1_8, "width": 1_8} ) a__ : Dict =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 _lowercase ( self ) -> Any: '''simple docstring''' pass def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Dict =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : Optional[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : List[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 a__ : Dict =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> int: '''simple docstring''' a__ : str =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input a__ : List[str] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a__ : Union[str, Any] =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : int =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input a__ : Optional[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 a__ : str =image_processing(lowerCAmelCase__ , 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"], ) , )
95
1
from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class __lowerCAmelCase : def __init__( self , lowerCAmelCase__ , ) -> Optional[Any]: '''simple docstring''' a__ : Optional[Any] =parent a__ : List[Any] =1_3 a__ : Optional[Any] =7 a__ : List[Any] =3_0 a__ : Optional[int] =self.seq_length + self.mem_len a__ : str =1_5 a__ : Tuple =True a__ : Tuple =True a__ : int =9_9 a__ : Union[str, Any] =[1_0, 5_0, 8_0] a__ : Dict =3_2 a__ : List[Any] =3_2 a__ : Dict =4 a__ : int =8 a__ : Tuple =1_2_8 a__ : Union[str, Any] =2 a__ : Tuple =2 a__ : Any =None a__ : List[str] =1 a__ : Optional[Any] =0 a__ : Any =3 a__ : Any =self.vocab_size - 1 a__ : int =0.01 def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : int =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Optional[Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Optional[int] =None if self.use_labels: a__ : str =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Union[str, Any] =TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def _lowercase ( self ) -> int: '''simple docstring''' random.seed(self.seed ) tf.random.set_seed(self.seed ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> str: '''simple docstring''' a__ : List[Any] =TFTransfoXLModel(lowerCAmelCase__ ) a__ , a__ : Dict =model(lowerCAmelCase__ ).to_tuple() a__ : List[Any] ={"input_ids": input_ids_a, "mems": mems_a} a__ , a__ : str =model(lowerCAmelCase__ ).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' a__ : Union[str, Any] =TFTransfoXLLMHeadModel(lowerCAmelCase__ ) a__ , a__ : Optional[Any] =model(lowerCAmelCase__ ).to_tuple() a__ : Optional[int] ={"input_ids": input_ids_a, "labels": lm_labels} a__ , a__ : Optional[int] =model(lowerCAmelCase__ ).to_tuple() a__ , a__ : int =model([input_ids_a, mems_a] ).to_tuple() a__ : int ={"input_ids": input_ids_a, "mems": mems_a, "labels": lm_labels} a__ , a__ : str =model(lowerCAmelCase__ ).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' a__ : Optional[Any] =TFTransfoXLForSequenceClassification(lowerCAmelCase__ ) a__ : int =model(lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self ) -> int: '''simple docstring''' a__ : int =self.prepare_config_and_inputs() ((a__) , (a__) , (a__) , (a__)) : List[Any] =config_and_inputs a__ : List[str] ={"input_ids": input_ids_a} return config, inputs_dict @require_tf class __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase): _lowercase : Union[str, Any] = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) _lowercase : Optional[Any] = () if is_tf_available() else () _lowercase : Optional[int] = ( { """feature-extraction""": TFTransfoXLModel, """text-classification""": TFTransfoXLForSequenceClassification, """text-generation""": TFTransfoXLLMHeadModel, """zero-shot""": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented _lowercase : Dict = False _lowercase : Optional[Any] = False _lowercase : List[str] = False _lowercase : str = False def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : Tuple =TFTransfoXLModelTester(self ) a__ : List[Any] =ConfigTester(self , config_class=lowerCAmelCase__ , d_embed=3_7 ) def _lowercase ( self ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' self.model_tester.set_seed() a__ : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*lowerCAmelCase__ ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' self.model_tester.set_seed() a__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*lowerCAmelCase__ ) def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*lowerCAmelCase__ ) def _lowercase ( self ) -> Dict: '''simple docstring''' a__ , a__ : List[str] =self.model_tester.prepare_config_and_inputs_for_common() a__ : str =[TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: a__ : Dict =model_class(lowerCAmelCase__ ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: a__ : Union[str, Any] =model.get_output_embeddings() assert isinstance(lowerCAmelCase__ , tf.keras.layers.Layer ) a__ : str =model.get_bias() assert name is None else: a__ : Dict =model.get_output_embeddings() assert x is None a__ : Dict =model.get_bias() assert name is None def _lowercase ( self ) -> List[str]: '''simple docstring''' pass @slow def _lowercase ( self ) -> Any: '''simple docstring''' for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : str =TFTransfoXLModel.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) @unittest.skip(reason="This model doesn't play well with fit() due to not returning a single loss." ) def _lowercase ( self ) -> List[str]: '''simple docstring''' pass @require_tf class __lowerCAmelCase ( unittest.TestCase): @unittest.skip("Skip test until #12651 is resolved." ) @slow def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : str =TFTransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103" ) # fmt: off a__ : Tuple =tf.convert_to_tensor([[3_3,1_2_9_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_2,1_7_0_6,1_7,2_0_0_9_8,5,3_2_1_5,2_1,3_7,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,6_2_2_4,8_3_1,1_6_0_0_2,2,8,6_0_3,7_8_9_6_7,2_9_5_4_6,2_3,8_0_3,2_0,2_5,4_1_6,5,8,2_3_2,4,2_7_7,6,1_8_5_5,4_6_0_1,3,2_9_5_4_6,5_4,8,3_6_0_9,5,5_7_2_1_1,4_9,4,1,2_7_7,1_8,8,1_7_5_5,1_5_6_9_1,3,3_4_1,2_5,4_1_6,6_9_3,4_2_5_7_3,7_1,1_7,4_0_1,9_4,3_1,1_7_9_1_9,2,2_9_5_4_6,7_8_7_3,1_8,1,4_3_5,2_3,1_1_0_1_1,7_5_5,5,5_1_6_7,3,7_9_8_3,9_8,8_4,2,2_9_5_4_6,3_2_6_7,8,3_6_0_9,4,1,4_8_6_5,1_0_7_5,2,6_0_8_7,7_1,6,3_4_6,8,5_8_5_4,3,2_9_5_4_6,8_2_4,1_4_0_0,1_8_6_8,2,1_9,1_6_0,2,3_1_1,8,5_4_9_6,2,2_0_9_2_0,1_7,2_5,1_5_0_9_7,3,2_4,2_4,0]] , dtype=tf.intaa ) # noqa: E231 # fmt: on # 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> # fmt: off a__ : Union[str, Any] =[3_3,1_2_9_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_2,1_7_0_6,1_7,2_0_0_9_8,5,3_2_1_5,2_1,3_7,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,6_2_2_4,8_3_1,1_6_0_0_2,2,8,6_0_3,7_8_9_6_7,2_9_5_4_6,2_3,8_0_3,2_0,2_5,4_1_6,5,8,2_3_2,4,2_7_7,6,1_8_5_5,4_6_0_1,3,2_9_5_4_6,5_4,8,3_6_0_9,5,5_7_2_1_1,4_9,4,1,2_7_7,1_8,8,1_7_5_5,1_5_6_9_1,3,3_4_1,2_5,4_1_6,6_9_3,4_2_5_7_3,7_1,1_7,4_0_1,9_4,3_1,1_7_9_1_9,2,2_9_5_4_6,7_8_7_3,1_8,1,4_3_5,2_3,1_1_0_1_1,7_5_5,5,5_1_6_7,3,7_9_8_3,9_8,8_4,2,2_9_5_4_6,3_2_6_7,8,3_6_0_9,4,1,4_8_6_5,1_0_7_5,2,6_0_8_7,7_1,6,3_4_6,8,5_8_5_4,3,2_9_5_4_6,8_2_4,1_4_0_0,1_8_6_8,2,1_9,1_6_0,2,3_1_1,8,5_4_9_6,2,2_0_9_2_0,1_7,2_5,1_5_0_9_7,3,2_4,2_4,0,3_3,1,1_8_5_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_8,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of 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. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> a__ : List[Any] =model.generate(lowerCAmelCase__ , max_length=2_0_0 , do_sample=lowerCAmelCase__ ) self.assertListEqual(output_ids[0].numpy().tolist() , lowerCAmelCase__ )
95
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Any = { """configuration_convbert""": ["""CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvBertConfig""", """ConvBertOnnxConfig"""], """tokenization_convbert""": ["""ConvBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] = ["""ConvBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[str] = [ """CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConvBertForMaskedLM""", """ConvBertForMultipleChoice""", """ConvBertForQuestionAnswering""", """ConvBertForSequenceClassification""", """ConvBertForTokenClassification""", """ConvBertLayer""", """ConvBertModel""", """ConvBertPreTrainedModel""", """load_tf_weights_in_convbert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ """TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFConvBertForMaskedLM""", """TFConvBertForMultipleChoice""", """TFConvBertForQuestionAnswering""", """TFConvBertForSequenceClassification""", """TFConvBertForTokenClassification""", """TFConvBertLayer""", """TFConvBertModel""", """TFConvBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
95
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer UpperCAmelCase : Tuple = logging.get_logger(__name__) UpperCAmelCase : Any = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase : int = { """vocab_file""": { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt""" ), } } UpperCAmelCase : int = { """junnyu/roformer_chinese_small""": 1536, """junnyu/roformer_chinese_base""": 1536, """junnyu/roformer_chinese_char_small""": 512, """junnyu/roformer_chinese_char_base""": 512, """junnyu/roformer_small_discriminator""": 128, """junnyu/roformer_small_generator""": 128, } UpperCAmelCase : Tuple = { """junnyu/roformer_chinese_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_base""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True}, """junnyu/roformer_small_discriminator""": {"""do_lower_case""": True}, """junnyu/roformer_small_generator""": {"""do_lower_case""": True}, } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Any = VOCAB_FILES_NAMES _lowercase : List[str] = PRETRAINED_VOCAB_FILES_MAP _lowercase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : str = PRETRAINED_INIT_CONFIGURATION _lowercase : List[str] = RoFormerTokenizer def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__="[UNK]" , lowerCAmelCase__="[SEP]" , lowerCAmelCase__="[PAD]" , lowerCAmelCase__="[CLS]" , lowerCAmelCase__="[MASK]" , lowerCAmelCase__=True , lowerCAmelCase__=None , **lowerCAmelCase__ , ) -> List[Any]: '''simple docstring''' super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , tokenize_chinese_chars=lowerCAmelCase__ , strip_accents=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : int =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , lowerCAmelCase__ ) != do_lower_case or pre_tok_state.get("strip_accents" , lowerCAmelCase__ ) != strip_accents ): a__ : int =getattr(lowerCAmelCase__ , pre_tok_state.pop("type" ) ) a__ : int =do_lower_case a__ : List[str] =strip_accents a__ : Union[str, Any] =pre_tok_class(**lowerCAmelCase__ ) a__ : List[str] =do_lower_case def __getstate__( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] =self.__dict__.copy() a__ : Optional[int] =BertPreTokenizer() return state def __setstate__( self , lowerCAmelCase__ ) -> str: '''simple docstring''' a__ : List[str] =d a__ : Any =self.__dict__["_tokenizer"].get_vocab() a__ : Any =PreTokenizer.custom(JiebaPreTokenizer(lowerCAmelCase__ ) ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> Optional[Any]: '''simple docstring''' a__ : Dict =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: '''simple docstring''' a__ : Any =[self.sep_token_id] a__ : int =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: '''simple docstring''' a__ : Optional[Any] =self._tokenizer.model.save(lowerCAmelCase__ , name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=False , **lowerCAmelCase__ , ) -> Any: '''simple docstring''' a__ : Dict =BertPreTokenizer() return super().save_pretrained(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ )
95
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : Tuple = { """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Any = """swin2sr""" _lowercase : Tuple = { """hidden_size""": """embed_dim""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , lowerCAmelCase__=6_4 , lowerCAmelCase__=1 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8_0 , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=8 , lowerCAmelCase__=2.0 , lowerCAmelCase__=True , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__="gelu" , lowerCAmelCase__=False , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-5 , lowerCAmelCase__=2 , lowerCAmelCase__=1.0 , lowerCAmelCase__="1conv" , lowerCAmelCase__="pixelshuffle" , **lowerCAmelCase__ , ) -> int: '''simple docstring''' super().__init__(**lowerCAmelCase__ ) a__ : Optional[Any] =image_size a__ : Dict =patch_size a__ : Tuple =num_channels a__ : Union[str, Any] =embed_dim a__ : Optional[Any] =depths a__ : List[str] =len(lowerCAmelCase__ ) a__ : Any =num_heads a__ : Any =window_size a__ : str =mlp_ratio a__ : List[str] =qkv_bias a__ : Dict =hidden_dropout_prob a__ : List[str] =attention_probs_dropout_prob a__ : Dict =drop_path_rate a__ : Optional[Any] =hidden_act a__ : Union[str, Any] =use_absolute_embeddings a__ : Optional[Any] =layer_norm_eps a__ : List[Any] =initializer_range a__ : int =upscale a__ : Optional[int] =img_range a__ : Any =resi_connection a__ : Optional[Any] =upsampler
95
1
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def _A ( SCREAMING_SNAKE_CASE : dict ): """simple docstring""" return (data["data"], data["target"]) def _A ( SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : np.ndarray ): """simple docstring""" a__ : Tuple =XGBClassifier() classifier.fit(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return classifier def _A ( ): """simple docstring""" a__ : Optional[Any] =load_iris() a__ , a__ : Union[str, Any] =data_handling(SCREAMING_SNAKE_CASE ) a__ , a__ , a__ , a__ : int =train_test_split( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , test_size=0.2_5 ) a__ : List[str] =iris["target_names"] # Create an XGBoost Classifier from the training data a__ : Union[str, Any] =xgboost(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , display_labels=SCREAMING_SNAKE_CASE , cmap="Blues" , normalize="true" , ) plt.title("Normalized Confusion Matrix - IRIS Dataset" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
95
from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class __lowerCAmelCase : pass
95
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : Tuple = { """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Any = """swin2sr""" _lowercase : Tuple = { """hidden_size""": """embed_dim""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , lowerCAmelCase__=6_4 , lowerCAmelCase__=1 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8_0 , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=8 , lowerCAmelCase__=2.0 , lowerCAmelCase__=True , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__="gelu" , lowerCAmelCase__=False , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-5 , lowerCAmelCase__=2 , lowerCAmelCase__=1.0 , lowerCAmelCase__="1conv" , lowerCAmelCase__="pixelshuffle" , **lowerCAmelCase__ , ) -> int: '''simple docstring''' super().__init__(**lowerCAmelCase__ ) a__ : Optional[Any] =image_size a__ : Dict =patch_size a__ : Tuple =num_channels a__ : Union[str, Any] =embed_dim a__ : Optional[Any] =depths a__ : List[str] =len(lowerCAmelCase__ ) a__ : Any =num_heads a__ : Any =window_size a__ : str =mlp_ratio a__ : List[str] =qkv_bias a__ : Dict =hidden_dropout_prob a__ : List[str] =attention_probs_dropout_prob a__ : Dict =drop_path_rate a__ : Optional[Any] =hidden_act a__ : Union[str, Any] =use_absolute_embeddings a__ : Optional[Any] =layer_norm_eps a__ : List[Any] =initializer_range a__ : int =upscale a__ : Optional[int] =img_range a__ : Any =resi_connection a__ : Optional[Any] =upsampler
95
# 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 __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = """philschmid/bart-large-cnn-samsum""" _lowercase : List[Any] = ( """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.""" ) _lowercase : Any = """summarizer""" _lowercase : Any = AutoTokenizer _lowercase : str = AutoModelForSeqaSeqLM _lowercase : Optional[int] = ["""text"""] _lowercase : Optional[int] = ["""text"""] def _lowercase ( self , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' return self.pre_processor(lowerCAmelCase__ , return_tensors="pt" , truncation=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return self.model.generate(**lowerCAmelCase__ )[0] def _lowercase ( self , lowerCAmelCase__ ) -> Any: '''simple docstring''' return self.pre_processor.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ )
95
1
import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow UpperCAmelCase : Tuple = False class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self , lowerCAmelCase__=3_2 ) -> Tuple: '''simple docstring''' set_seed(0 ) a__ : Optional[int] =UNetaDModel(sample_size=lowerCAmelCase__ , in_channels=3 , out_channels=3 ) a__ : Optional[int] =torch.optim.SGD(model.parameters() , lr=0.00_01 ) return model, optimizer @slow def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Any ="cpu" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable a__ : Optional[Any] =DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_start=0.00_01 , beta_end=0.02 , beta_schedule="linear" , clip_sample=lowerCAmelCase__ , ) a__ : Any =DDIMScheduler( num_train_timesteps=1_0_0_0 , beta_start=0.00_01 , beta_end=0.02 , beta_schedule="linear" , clip_sample=lowerCAmelCase__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) a__ : Tuple =[torch.randn((4, 3, 3_2, 3_2) ).clip(-1 , 1 ).to(lowerCAmelCase__ ) for _ in range(4 )] a__ : Tuple =[torch.randn((4, 3, 3_2, 3_2) ).to(lowerCAmelCase__ ) for _ in range(4 )] a__ : Union[str, Any] =[torch.randint(0 , 1_0_0_0 , (4,) ).long().to(lowerCAmelCase__ ) for _ in range(4 )] # train with a DDPM scheduler a__ , a__ : Optional[Any] =self.get_model_optimizer(resolution=3_2 ) model.train().to(lowerCAmelCase__ ) for i in range(4 ): optimizer.zero_grad() a__ : List[Any] =ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) a__ : Optional[int] =model(lowerCAmelCase__ , timesteps[i] ).sample a__ : int =torch.nn.functional.mse_loss(lowerCAmelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM a__ , a__ : List[str] =self.get_model_optimizer(resolution=3_2 ) model.train().to(lowerCAmelCase__ ) for i in range(4 ): optimizer.zero_grad() a__ : Union[str, Any] =ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) a__ : Optional[Any] =model(lowerCAmelCase__ , timesteps[i] ).sample a__ : List[Any] =torch.nn.functional.mse_loss(lowerCAmelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-5 ) ) self.assertTrue(torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-5 ) )
95
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer UpperCAmelCase : int = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase : List[Any] = [ """small""", """small-base""", """medium""", """medium-base""", """intermediate""", """intermediate-base""", """large""", """large-base""", """xlarge""", """xlarge-base""", ] UpperCAmelCase : Optional[int] = { """vocab_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt""", """funnel-transformer/small-base""": """https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt""", """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt""", """funnel-transformer/large-base""": """https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt""", """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json""", """funnel-transformer/small-base""": ( """https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json""" ), """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json""", """funnel-transformer/large-base""": ( """https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json""" ), """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json""" ), }, } UpperCAmelCase : Optional[int] = {F"""funnel-transformer/{name}""": 512 for name in _model_names} UpperCAmelCase : Optional[int] = {F"""funnel-transformer/{name}""": {"""do_lower_case""": True} for name in _model_names} class __lowerCAmelCase ( UpperCamelCase__): _lowercase : str = VOCAB_FILES_NAMES _lowercase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowercase : Dict = PRETRAINED_INIT_CONFIGURATION _lowercase : Union[str, Any] = FunnelTokenizer _lowercase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : int = 2 def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<sep>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="<cls>" , lowerCAmelCase__="<mask>" , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__="##" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , clean_text=lowerCAmelCase__ , tokenize_chinese_chars=lowerCAmelCase__ , strip_accents=lowerCAmelCase__ , wordpieces_prefix=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : Optional[Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowerCAmelCase__ ) != do_lower_case or normalizer_state.get("strip_accents" , lowerCAmelCase__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowerCAmelCase__ ) != tokenize_chinese_chars ): a__ : List[str] =getattr(lowerCAmelCase__ , normalizer_state.pop("type" ) ) a__ : Union[str, Any] =do_lower_case a__ : Any =strip_accents a__ : Optional[Any] =tokenize_chinese_chars a__ : Dict =normalizer_class(**lowerCAmelCase__ ) a__ : Any =do_lower_case def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> str: '''simple docstring''' a__ : Dict =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] =[self.sep_token_id] a__ : Union[str, Any] =[self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: '''simple docstring''' a__ : Tuple =self._tokenizer.model.save(lowerCAmelCase__ , name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ )
95
1
# limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> str: '''simple docstring''' super().__init__() self.register_modules(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ ) @torch.no_grad() def __call__( self , lowerCAmelCase__ = 1 , lowerCAmelCase__ = None , lowerCAmelCase__ = 5_0 , lowerCAmelCase__ = "pil" , lowerCAmelCase__ = True , **lowerCAmelCase__ , ) -> Union[ImagePipelineOutput, Tuple]: '''simple docstring''' a__ : int =torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=lowerCAmelCase__ , ) a__ : Union[str, Any] =image.to(self.device ) # set step values self.scheduler.set_timesteps(lowerCAmelCase__ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output a__ : Any =self.unet(lowerCAmelCase__ , lowerCAmelCase__ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 a__ : List[str] =self.scheduler.step(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ).prev_sample a__ : Union[str, Any] =(image / 2 + 0.5).clamp(0 , 1 ) a__ : str =image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ : Any =self.numpy_to_pil(lowerCAmelCase__ ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=lowerCAmelCase__ ), "This is a local test"
95
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 ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = "arrow" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( split=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ , streaming=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : int =load_from_cache_file a__ : Tuple =file_format a__ : List[Any] =Spark( df=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , working_dir=lowerCAmelCase__ , **lowerCAmelCase__ , ) def _lowercase ( self ) -> str: '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) a__ : str =None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowerCAmelCase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
95
1
from decimal import Decimal, getcontext from math import ceil, factorial def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise TypeError("Undefined for non-integers" ) elif precision < 1: raise ValueError("Undefined for non-natural numbers" ) a__ : Tuple =precision a__ : List[Any] =ceil(precision / 14 ) a__ : Tuple =426_880 * Decimal(10_005 ).sqrt() a__ : List[Any] =1 a__ : str =13_591_409 a__ : Any =Decimal(SCREAMING_SNAKE_CASE ) for k in range(1 , SCREAMING_SNAKE_CASE ): a__ : Any =factorial(6 * k ) // (factorial(3 * k ) * factorial(SCREAMING_SNAKE_CASE ) ** 3) linear_term += 545_140_134 exponential_term *= -262_537_412_640_768_000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": UpperCAmelCase : Optional[int] = 50 print(F"""The first {n} digits of pi is: {pi(n)}""")
95
from math import pi def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
95
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : List[str] = { """configuration_timesformer""": ["""TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TimesformerConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : str = [ """TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TimesformerModel""", """TimesformerForVideoClassification""", """TimesformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys UpperCAmelCase : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
95
import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging UpperCAmelCase : int = { """cola""": 2, """mnli""": 3, """mrpc""": 2, """sst-2""": 2, """sts-b""": 1, """qqp""": 2, """qnli""": 2, """rte""": 2, """wnli""": 2, } logging.set_verbosity_info() def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any]=None ): """simple docstring""" a__ : Optional[int] =XLNetConfig.from_json_file(SCREAMING_SNAKE_CASE ) a__ : Dict =finetuning_task.lower() if finetuning_task is not None else "" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(f'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}''' ) a__ : List[str] =finetuning_task a__ : Tuple =GLUE_TASKS_NUM_LABELS[finetuning_task] a__ : List[Any] =XLNetForSequenceClassification(SCREAMING_SNAKE_CASE ) elif "squad" in finetuning_task: a__ : Optional[int] =finetuning_task a__ : Dict =XLNetForQuestionAnswering(SCREAMING_SNAKE_CASE ) else: a__ : List[Any] =XLNetLMHeadModel(SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Save pytorch-model a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print(f'''Save PyTorch model to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE ) print(f'''Save configuration file to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--xlnet_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained XLNet model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the folder to store the PyTorch model or dataset/vocab.""", ) parser.add_argument( """--finetuning_task""", default=None, type=str, help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""", ) UpperCAmelCase : int = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
95
1
def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Any =0 a__ : List[Any] =number while duplicate > 0: a__ , a__ : Dict =divmod(SCREAMING_SNAKE_CASE , 10 ) fact_sum += factorial(SCREAMING_SNAKE_CASE ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") UpperCAmelCase : Optional[Any] = int(input("""Enter number: """).strip()) print( F"""{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.""" )
95
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { """google/canine-s""": """https://huggingface.co/google/canine-s/resolve/main/config.json""", # See all CANINE models at https://huggingface.co/models?filter=canine } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[Any] = """canine""" def __init__( self , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_6 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=0 , lowerCAmelCase__=0XE0_00 , lowerCAmelCase__=0XE0_01 , lowerCAmelCase__=4 , lowerCAmelCase__=4 , lowerCAmelCase__=8 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_2_8 , **lowerCAmelCase__ , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Optional[int] =max_position_embeddings a__ : str =hidden_size a__ : Optional[Any] =num_hidden_layers a__ : Tuple =num_attention_heads a__ : Optional[Any] =intermediate_size a__ : Optional[int] =hidden_act a__ : List[Any] =hidden_dropout_prob a__ : Union[str, Any] =attention_probs_dropout_prob a__ : Optional[Any] =initializer_range a__ : Union[str, Any] =type_vocab_size a__ : Optional[int] =layer_norm_eps # Character config: a__ : int =downsampling_rate a__ : Optional[Any] =upsampling_kernel_size a__ : Union[str, Any] =num_hash_functions a__ : Any =num_hash_buckets a__ : int =local_transformer_stride
95
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase : int = { """configuration_efficientnet""": [ """EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EfficientNetConfig""", """EfficientNetOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[int] = ["""EfficientNetImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict = [ """EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """EfficientNetForImageClassification""", """EfficientNetModel""", """EfficientNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys UpperCAmelCase : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
95
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device UpperCAmelCase : int = False class __lowerCAmelCase ( unittest.TestCase): pass @nightly @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Optional[Any] =torch.manual_seed(0 ) a__ : Optional[Any] =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCAmelCase__ ) a__ : str =VersatileDiffusionPipeline.from_pretrained(lowerCAmelCase__ , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] =generator.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] ="cyberpunk 2077" a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Union[str, Any] =torch.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images a__ : int =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : str ="A painting of a squirrel eating a burger " a__ : Optional[int] =torch.manual_seed(0 ) a__ : str =pipe.text_to_image( prompt=lowerCAmelCase__ , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" ).images a__ : Any =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Optional[int] =np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : Optional[Any] =pipe.image_variation(lowerCAmelCase__ , generator=lowerCAmelCase__ , output_type="numpy" ).images a__ : Union[str, Any] =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
95
1
import math def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _A ( SCREAMING_SNAKE_CASE : int = 10_001 ): """simple docstring""" try: a__ : Optional[int] =int(SCREAMING_SNAKE_CASE ) 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__ : list[int] =[] a__ : int =2 while len(SCREAMING_SNAKE_CASE ) < nth: if is_prime(SCREAMING_SNAKE_CASE ): primes.append(SCREAMING_SNAKE_CASE ) num += 1 else: num += 1 return primes[len(SCREAMING_SNAKE_CASE ) - 1] if __name__ == "__main__": print(F"""{solution() = }""")
95
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class __lowerCAmelCase : def _lowercase ( self , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError() def _lowercase ( self ) -> int: '''simple docstring''' raise NotImplementedError() class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , **lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : str =tokenizer a__ : List[str] =skip_prompt a__ : List[Any] =decode_kwargs # variables used in the streaming process a__ : Dict =[] a__ : int =0 a__ : str =True def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError("TextStreamer only supports batch size 1" ) elif len(value.shape ) > 1: a__ : Any =value[0] if self.skip_prompt and self.next_tokens_are_prompt: a__ : Dict =False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith("\n" ): a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 # If the last token is a CJK character, we print the characters. elif len(lowerCAmelCase__ ) > 0 and self._is_chinese_char(ord(text[-1] ) ): a__ : List[str] =text[self.print_len :] self.print_len += len(lowerCAmelCase__ ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: a__ : str =text[self.print_len : text.rfind(" " ) + 1] self.print_len += len(lowerCAmelCase__ ) self.on_finalized_text(lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' if len(self.token_cache ) > 0: a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 else: a__ : Union[str, Any] ="" a__ : Any =True self.on_finalized_text(lowerCAmelCase__ , stream_end=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> Optional[Any]: '''simple docstring''' print(lowerCAmelCase__ , flush=lowerCAmelCase__ , end="" if not stream_end else None ) def _lowercase ( self , lowerCAmelCase__ ) -> str: '''simple docstring''' if ( (cp >= 0X4E_00 and cp <= 0X9F_FF) or (cp >= 0X34_00 and cp <= 0X4D_BF) # or (cp >= 0X2_00_00 and cp <= 0X2_A6_DF) # or (cp >= 0X2_A7_00 and cp <= 0X2_B7_3F) # or (cp >= 0X2_B7_40 and cp <= 0X2_B8_1F) # or (cp >= 0X2_B8_20 and cp <= 0X2_CE_AF) # or (cp >= 0XF9_00 and cp <= 0XFA_FF) or (cp >= 0X2_F8_00 and cp <= 0X2_FA_1F) # ): # return True return False class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , lowerCAmelCase__ = None , **lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' super().__init__(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : str =Queue() a__ : Optional[Any] =None a__ : Any =timeout def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> List[str]: '''simple docstring''' self.text_queue.put(lowerCAmelCase__ , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self ) -> Dict: '''simple docstring''' return self def _lowercase ( self ) -> int: '''simple docstring''' a__ : int =self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
95
1
from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def _A ( SCREAMING_SNAKE_CASE : str = "laptop" ): """simple docstring""" a__ : Optional[int] =f'''https://www.amazon.in/laptop/s?k={product}''' a__ : List[str] ={ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36", "Accept-Language": "en-US, en;q=0.5", } a__ : Union[str, Any] =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE , headers=SCREAMING_SNAKE_CASE ).text ) # Initialize a Pandas dataframe with the column titles a__ : Optional[int] =DataFrame( columns=[ "Product Title", "Product Link", "Current Price of the product", "Product Rating", "MRP of the product", "Discount", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( "div" , attrs={"class": "s-result-item", "data-component-type": "s-search-result"} , ) , soup.find_all("div" , attrs={"class": "a-row a-size-base a-color-base"} ) , ): try: a__ : Optional[int] =item.ha.text a__ : List[str] ="https://www.amazon.in/" + item.ha.a["href"] a__ : Any =item.find("span" , attrs={"class": "a-offscreen"} ).text try: a__ : Tuple =item.find("span" , attrs={"class": "a-icon-alt"} ).text except AttributeError: a__ : List[str] ="Not available" try: a__ : List[str] =( "₹" + item.find( "span" , attrs={"class": "a-price a-text-price"} ).text.split("₹" )[1] ) except AttributeError: a__ : str ="" try: a__ : List[str] =float( ( ( float(product_mrp.strip("₹" ).replace("," , "" ) ) - float(product_price.strip("₹" ).replace("," , "" ) ) ) / float(product_mrp.strip("₹" ).replace("," , "" ) ) ) * 100 ) except ValueError: a__ : Dict =float("nan" ) except AttributeError: pass a__ : Optional[Any] =[ product_title, product_link, product_price, product_rating, product_mrp, discount, ] a__ : Optional[Any] =" " a__ : Optional[int] =" " data_frame.index += 1 return data_frame if __name__ == "__main__": UpperCAmelCase : List[str] = """headphones""" get_amazon_product_data(product).to_csv(F"""Amazon Product Data for {product}.csv""")
95
def _A ( SCREAMING_SNAKE_CASE : int = 50 ): """simple docstring""" a__ : Any =[1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
95
1
UpperCAmelCase : Tuple = """Alexander Joslin""" import operator as op from .stack import Stack def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" a__ : str ={"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} a__ : Stack[int] =Stack() a__ : Stack[str] =Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(SCREAMING_SNAKE_CASE ) ) elif i in operators: # RULE 2 operator_stack.push(SCREAMING_SNAKE_CASE ) elif i == ")": # RULE 4 a__ : Dict =operator_stack.peek() operator_stack.pop() a__ : Optional[Any] =operand_stack.peek() operand_stack.pop() a__ : Tuple =operand_stack.peek() operand_stack.pop() a__ : Any =operators[opr](SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) operand_stack.push(SCREAMING_SNAKE_CASE ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": UpperCAmelCase : Optional[int] = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
95
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if len(SCREAMING_SNAKE_CASE ) == 0: return [] a__ , a__ : int =min(SCREAMING_SNAKE_CASE ), max(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =int(max_value - min_value ) + 1 a__ : list[list] =[[] for _ in range(SCREAMING_SNAKE_CASE )] for i in my_list: buckets[int(i - min_value )].append(SCREAMING_SNAKE_CASE ) return [v for bucket in buckets for v in sorted(SCREAMING_SNAKE_CASE )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
95
1
def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" a__ : Optional[int] =[int(SCREAMING_SNAKE_CASE ) for i in ip_va_address.split("." ) if i.isdigit()] return len(SCREAMING_SNAKE_CASE ) == 4 and all(0 <= int(SCREAMING_SNAKE_CASE ) <= 254 for octet in octets ) if __name__ == "__main__": UpperCAmelCase : Optional[int] = input().strip() UpperCAmelCase : Optional[int] = """valid""" if is_ip_va_address_valid(ip) else """invalid""" print(F"""{ip} is a {valid_or_invalid} IP v4 address.""")
95
import numpy as np def _A ( SCREAMING_SNAKE_CASE : np.array ): """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
95
1
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging UpperCAmelCase : Dict = logging.get_logger(__name__) class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Tuple = ["""pixel_values"""] def __init__( self , lowerCAmelCase__ = True , lowerCAmelCase__ = 1 / 2_5_5 , lowerCAmelCase__ = True , lowerCAmelCase__ = 8 , **lowerCAmelCase__ , ) -> None: '''simple docstring''' super().__init__(**lowerCAmelCase__ ) a__ : Optional[Any] =do_rescale a__ : Dict =rescale_factor a__ : Optional[Any] =do_pad a__ : Tuple =pad_size def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , **lowerCAmelCase__ ) -> np.ndarray: '''simple docstring''' return rescale(lowerCAmelCase__ , scale=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> str: '''simple docstring''' a__ , a__ : Tuple =get_image_size(lowerCAmelCase__ ) a__ : int =(old_height // size + 1) * size - old_height a__ : str =(old_width // size + 1) * size - old_width return pad(lowerCAmelCase__ , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = ChannelDimension.FIRST , **lowerCAmelCase__ , ) -> Dict: '''simple docstring''' a__ : List[Any] =do_rescale if do_rescale is not None else self.do_rescale a__ : Dict =rescale_factor if rescale_factor is not None else self.rescale_factor a__ : Tuple =do_pad if do_pad is not None else self.do_pad a__ : Tuple =pad_size if pad_size is not None else self.pad_size a__ : List[Any] =make_list_of_images(lowerCAmelCase__ ) if not valid_images(lowerCAmelCase__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. a__ : List[str] =[to_numpy_array(lowerCAmelCase__ ) for image in images] if do_rescale: a__ : Tuple =[self.rescale(image=lowerCAmelCase__ , scale=lowerCAmelCase__ ) for image in images] if do_pad: a__ : List[Any] =[self.pad(lowerCAmelCase__ , size=lowerCAmelCase__ ) for image in images] a__ : int =[to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__ ) for image in images] a__ : Union[str, Any] ={"pixel_values": images} return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__ )
95
import numpy # List of input, output pairs UpperCAmelCase : str = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) UpperCAmelCase : Optional[int] = (((515, 22, 13), 555), ((61, 35, 49), 150)) UpperCAmelCase : str = [2, 4, 1, 5] UpperCAmelCase : List[str] = len(train_data) UpperCAmelCase : Dict = 0.0_0_9 def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Tuple="train" ): """simple docstring""" return calculate_hypothesis_value(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) - output( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : Tuple =0 for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : int=m ): """simple docstring""" a__ : Any =0 for i in range(SCREAMING_SNAKE_CASE ): if index == -1: summation_value += _error(SCREAMING_SNAKE_CASE ) else: summation_value += _error(SCREAMING_SNAKE_CASE ) * train_data[i][0][index] return summation_value def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Any =summation_of_cost_derivative(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) / m return cost_derivative_value def _A ( ): """simple docstring""" global parameter_vector # Tune these values to set a tolerance value for predicted output a__ : Dict =0.0_0_0_0_0_2 a__ : Union[str, Any] =0 a__ : Any =0 while True: j += 1 a__ : Any =[0, 0, 0, 0] for i in range(0 , len(SCREAMING_SNAKE_CASE ) ): a__ : Tuple =get_cost_derivative(i - 1 ) a__ : List[Any] =( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE , rtol=SCREAMING_SNAKE_CASE , ): break a__ : Optional[Any] =temp_parameter_vector print(("Number of iterations:", j) ) def _A ( ): """simple docstring""" for i in range(len(SCREAMING_SNAKE_CASE ) ): print(("Actual output value:", output(SCREAMING_SNAKE_CASE , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(SCREAMING_SNAKE_CASE , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("""\nTesting gradient descent for a linear hypothesis function.\n""") test_gradient_descent()
95
1
from math import pi def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
95
def _A ( SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" a__ : Optional[Any] =len(SCREAMING_SNAKE_CASE ) while cur > 1: # Find the maximum number in arr a__ : List[Any] =arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi a__ : int =arr[mi::-1] + arr[mi + 1 : len(SCREAMING_SNAKE_CASE )] # Reverse whole list a__ : List[str] =arr[cur - 1 :: -1] + arr[cur : len(SCREAMING_SNAKE_CASE )] cur -= 1 return arr if __name__ == "__main__": UpperCAmelCase : int = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase : Optional[int] = [int(item) for item in user_input.split(""",""")] print(pancake_sort(unsorted))
95
1
from __future__ import annotations from scipy.special import comb # type: ignore class __lowerCAmelCase : def __init__( self , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' a__ : Any =list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. a__ : List[Any] =len(lowerCAmelCase__ ) - 1 def _lowercase ( self , lowerCAmelCase__ ) -> list[float]: '''simple docstring''' assert 0 <= t <= 1, "Time t must be between 0 and 1." a__ : list[float] =[] for i in range(len(self.list_of_points ) ): # basis function for each i output_values.append( comb(self.degree , lowerCAmelCase__ ) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(lowerCAmelCase__ ) , 5 ) == 1 return output_values def _lowercase ( self , lowerCAmelCase__ ) -> tuple[float, float]: '''simple docstring''' assert 0 <= t <= 1, "Time t must be between 0 and 1." a__ : Optional[Any] =self.basis_function(lowerCAmelCase__ ) a__ : Dict =0.0 a__ : Dict =0.0 for i in range(len(self.list_of_points ) ): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def _lowercase ( self , lowerCAmelCase__ = 0.01 ) -> Any: '''simple docstring''' from matplotlib import pyplot as plt # type: ignore a__ : list[float] =[] # x coordinates of points to plot a__ : list[float] =[] # y coordinates of points to plot a__ : Union[str, Any] =0.0 while t <= 1: a__ : Optional[int] =self.bezier_curve_function(lowerCAmelCase__ ) to_plot_x.append(value[0] ) to_plot_y.append(value[1] ) t += step_size a__ : List[Any] =[i[0] for i in self.list_of_points] a__ : Dict =[i[1] for i in self.list_of_points] plt.plot( lowerCAmelCase__ , lowerCAmelCase__ , color="blue" , label="Curve of Degree " + str(self.degree ) , ) plt.scatter(lowerCAmelCase__ , lowerCAmelCase__ , color="red" , label="Control Points" ) plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
95
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Any =tempfile.mkdtemp() # fmt: off a__ : List[Any] =["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on a__ : str =dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) a__ : List[Any] =["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""] a__ : Optional[int] ={"unk_token": "<unk>"} a__ : Optional[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) a__ : Tuple =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowerCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(lowerCAmelCase__ ) ) a__ : Optional[Any] ={ "do_resize": True, "size": 2_0, "do_center_crop": True, "crop_size": 1_8, "do_normalize": True, "image_mean": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], "image_std": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } a__ : Dict =os.path.join(self.tmpdirname , lowerCAmelCase__ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Any: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =[np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] a__ : List[Any] =[Image.fromarray(np.moveaxis(lowerCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Union[str, Any] =self.get_tokenizer() a__ : int =self.get_rust_tokenizer() a__ : List[str] =self.get_image_processor() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) a__ : Optional[Any] =CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=lowerCAmelCase__ ) a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) a__ : Dict =CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor , lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a__ : str =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) a__ : int =self.get_image_processor(do_normalize=lowerCAmelCase__ , padding_value=1.0 ) a__ : Optional[Any] =CLIPSegProcessor.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 _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : str =self.get_image_processor() a__ : Optional[int] =self.get_tokenizer() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : str =self.prepare_image_inputs() a__ : Any =image_processor(lowerCAmelCase__ , return_tensors="np" ) a__ : Optional[int] =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 _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : List[Any] =self.get_tokenizer() a__ : Optional[int] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Union[str, Any] ="lower newer" a__ : List[str] =processor(text=lowerCAmelCase__ ) a__ : str =tokenizer(lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =self.get_image_processor() a__ : Dict =self.get_tokenizer() a__ : Union[str, Any] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict ="lower newer" a__ : int =self.prepare_image_inputs() a__ : Any =processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> str: '''simple docstring''' a__ : Union[str, Any] =self.get_image_processor() a__ : Optional[Any] =self.get_tokenizer() a__ : str =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : int =self.prepare_image_inputs() a__ : Union[str, Any] =self.prepare_image_inputs() a__ : Tuple =processor(images=lowerCAmelCase__ , visual_prompt=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "conditional_pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : Any =self.get_tokenizer() a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a__ : Optional[Any] =processor.batch_decode(lowerCAmelCase__ ) a__ : Dict =tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
95
1
import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Dict: '''simple docstring''' self.assertEqual(len(lowerCAmelCase__ ) , len(lowerCAmelCase__ ) ) for a, b in zip(lowerCAmelCase__ , lowerCAmelCase__ ): self.assertAlmostEqual(lowerCAmelCase__ , lowerCAmelCase__ , delta=lowerCAmelCase__ ) def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : Optional[Any] =GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(lowerCAmelCase__ ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2 ) def _lowercase ( self ) -> int: '''simple docstring''' a__ : Any =None ops.enable_eager_execution_internal() a__ : int =tf.config.list_physical_devices("CPU" ) if len(lowerCAmelCase__ ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) a__ : Optional[int] =tf.config.list_logical_devices(device_type="CPU" ) a__ : List[str] =tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): a__ : int =GradientAccumulator() a__ : Optional[Any] =tf.Variable([4.0, 3.0] ) a__ , a__ : Dict =create_optimizer(5E-5 , 1_0 , 5 ) a__ : Optional[int] =tf.Variable([0.0, 0.0] , trainable=lowerCAmelCase__ ) def accumulate_on_replica(lowerCAmelCase__ ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(lowerCAmelCase__ , lowerCAmelCase__ ): with strategy.scope(): a__ : Optional[Any] =strategy.experimental_local_results(lowerCAmelCase__ ) local_variables[0].assign(lowerCAmelCase__ ) local_variables[1].assign(lowerCAmelCase__ ) strategy.run(lowerCAmelCase__ , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(lowerCAmelCase__ ) def _check_local_values(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Tuple =strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , lowerCAmelCase__ , tol=1E-2 ) self.assertListAlmostEqual(values[1].value() , lowerCAmelCase__ , tol=1E-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
95
def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) if len(SCREAMING_SNAKE_CASE ) == 1: return True a__ : Union[str, Any] =series[1] - series[0] for index in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) a__ : Any =0 for val in series: answer += val return answer / len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
95
1
def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input must be an integer" ) if input_num <= 0: raise ValueError("Input must be positive" ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
95
import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Tuple = """M-CLIP""" def __init__( self , lowerCAmelCase__=1_0_2_4 , lowerCAmelCase__=7_6_8 , **lowerCAmelCase__ ) -> Any: '''simple docstring''' a__ : int =transformerDimSize a__ : Dict =imageDimSize super().__init__(**lowerCAmelCase__ ) class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = MCLIPConfig def __init__( self , lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> List[str]: '''simple docstring''' super().__init__(lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Tuple =XLMRobertaModel(lowerCAmelCase__ ) a__ : List[str] =torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[Any] =self.transformer(input_ids=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ )[0] a__ : int =(embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(lowerCAmelCase__ ), embs
95
1
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Dict: '''simple docstring''' a__ : Any =params a__ : Dict =np.array(lowerCAmelCase__ ) a__ : Any =np.array([len(lowerCAmelCase__ ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , lowerCAmelCase__ ) -> str: '''simple docstring''' return (self.token_ids[index], self.lengths[index]) def __len__( self ) -> int: '''simple docstring''' return len(self.lengths ) def _lowercase ( self ) -> Any: '''simple docstring''' assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : Any =self.params.max_model_input_size a__ : List[str] =self.lengths > max_len logger.info(F'''Splitting {sum(lowerCAmelCase__ )} too long sequences.''' ) def divide_chunks(lowerCAmelCase__ , lowerCAmelCase__ ): return [l[i : i + n] for i in range(0 , len(lowerCAmelCase__ ) , lowerCAmelCase__ )] a__ : Optional[int] =[] a__ : Any =[] if self.params.mlm: a__ , a__ : List[str] =self.params.special_tok_ids["cls_token"], self.params.special_tok_ids["sep_token"] else: a__ , a__ : Union[str, Any] =self.params.special_tok_ids["bos_token"], self.params.special_tok_ids["eos_token"] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: a__ : Dict =[] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: a__ : int =np.insert(lowerCAmelCase__ , 0 , lowerCAmelCase__ ) if sub_s[-1] != sep_id: a__ : Tuple =np.insert(lowerCAmelCase__ , len(lowerCAmelCase__ ) , lowerCAmelCase__ ) assert len(lowerCAmelCase__ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(lowerCAmelCase__ ) new_tok_ids.extend(lowerCAmelCase__ ) new_lengths.extend([len(lowerCAmelCase__ ) for l in sub_seqs] ) a__ : Dict =np.array(lowerCAmelCase__ ) a__ : Dict =np.array(lowerCAmelCase__ ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Optional[Any] =len(self ) a__ : Tuple =self.lengths > 1_1 a__ : str =self.token_ids[indices] a__ : Optional[Any] =self.lengths[indices] a__ : Dict =len(self ) logger.info(F'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def _lowercase ( self ) -> List[Any]: '''simple docstring''' if "unk_token" not in self.params.special_tok_ids: return else: a__ : Any =self.params.special_tok_ids["unk_token"] a__ : Any =len(self ) a__ : int =np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) a__ : Optional[Any] =(unk_occs / self.lengths) < 0.5 a__ : Optional[Any] =self.token_ids[indices] a__ : Optional[Any] =self.lengths[indices] a__ : Any =len(self ) logger.info(F'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def _lowercase ( self ) -> Tuple: '''simple docstring''' if not self.params.is_master: return logger.info(F'''{len(self )} sequences''' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def _lowercase ( self , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' a__ : List[str] =[t[0] for t in batch] a__ : Optional[int] =[t[1] for t in batch] assert len(lowerCAmelCase__ ) == len(lowerCAmelCase__ ) # Max for paddings a__ : Optional[Any] =max(lowerCAmelCase__ ) # Pad token ids if self.params.mlm: a__ : str =self.params.special_tok_ids["pad_token"] else: a__ : Dict =self.params.special_tok_ids["unk_token"] a__ : Any =[list(t.astype(lowerCAmelCase__ ) ) + [pad_idx] * (max_seq_len_ - len(lowerCAmelCase__ )) for t in token_ids] assert len(tk_ ) == len(lowerCAmelCase__ ) assert all(len(lowerCAmelCase__ ) == max_seq_len_ for t in tk_ ) a__ : List[str] =torch.tensor(tk_ ) # (bs, max_seq_len_) a__ : List[Any] =torch.tensor(lowerCAmelCase__ ) # (bs) return tk_t, lg_t
95
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 ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to properly calculate the metrics on the # validation dataset when in a distributed system, and builds off the # `nlp_example.py` script. # # 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 help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # 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 : Any = 16 UpperCAmelCase : str = 32 def _A ( SCREAMING_SNAKE_CASE : Accelerator , SCREAMING_SNAKE_CASE : int = 16 ): """simple docstring""" a__ : int =AutoTokenizer.from_pretrained("bert-base-cased" ) a__ : List[str] =load_dataset("glue" , "mrpc" ) def tokenize_function(SCREAMING_SNAKE_CASE : List[Any] ): # max_length=None => use the model max length (it's actually the default) a__ : int =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__ : Dict =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__ : Dict =tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(SCREAMING_SNAKE_CASE : str ): # On TPU it's best to pad everything to the same length or training will be very slow. a__ : Optional[Any] =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__ : str =16 elif accelerator.mixed_precision != "no": a__ : Union[str, Any] =8 else: a__ : List[str] =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__ : Any =DataLoader( tokenized_datasets["train"] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE ) a__ : int =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 : str = mocked_dataloaders # noqa: F811 def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : str ): """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , SCREAMING_SNAKE_CASE ) == "1": a__ : Tuple =2 # Initialize accelerator a__ : int =Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a__ : Optional[int] =config["lr"] a__ : Union[str, Any] =int(config["num_epochs"] ) a__ : Any =int(config["seed"] ) a__ : Dict =int(config["batch_size"] ) a__ : int =evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation a__ : int =1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: a__ : Dict =batch_size // MAX_GPU_BATCH_SIZE a__ : Tuple =MAX_GPU_BATCH_SIZE set_seed(SCREAMING_SNAKE_CASE ) a__ , a__ : Optional[int] =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__ : List[str] =model.to(accelerator.device ) # Instantiate optimizer a__ : List[Any] =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) // gradient_accumulation_steps , ) # 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__ : Optional[int] =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() 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 ) a__ : Dict =model(**SCREAMING_SNAKE_CASE ) a__ : List[Any] =outputs.loss a__ : List[str] =loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() a__ : Optional[Any] =0 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__ : Any =model(**SCREAMING_SNAKE_CASE ) a__ : str =outputs.logits.argmax(dim=-1 ) a__ , a__ : List[str] =accelerator.gather((predictions, batch["labels"]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(SCREAMING_SNAKE_CASE ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples a__ : Optional[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] a__ : Dict =references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=SCREAMING_SNAKE_CASE , references=SCREAMING_SNAKE_CASE , ) a__ : Tuple =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , SCREAMING_SNAKE_CASE ) def _A ( ): """simple docstring""" a__ : List[str] =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." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) a__ : str =parser.parse_args() a__ : Optional[int] ={"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
95
1
import numpy class __lowerCAmelCase : def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> None: '''simple docstring''' a__ : int =input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. a__ : List[str] =numpy.random.rand( self.input_array.shape[1] , 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. a__ : int =numpy.random.rand( 4 , 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. a__ : Any =numpy.random.rand(3 , 1 ) # Real output values provided. a__ : str =output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. a__ : str =numpy.zeros(output_array.shape ) def _lowercase ( self ) -> numpy.ndarray: '''simple docstring''' a__ : List[Any] =sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. a__ : Optional[Any] =sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. a__ : Dict =sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return self.layer_between_second_hidden_layer_and_output def _lowercase ( self ) -> None: '''simple docstring''' a__ : Any =numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , ) a__ : Any =numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , ) a__ : Optional[int] =numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> None: '''simple docstring''' for iteration in range(1 , iterations + 1 ): a__ : Optional[Any] =self.feedforward() self.back_propagation() if give_loss: a__ : Optional[Any] =numpy.mean(numpy.square(output - self.feedforward() ) ) print(F'''Iteration {iteration} Loss: {loss}''' ) def _lowercase ( self , lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : List[Any] =input_arr a__ : Optional[int] =sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) ) a__ : Union[str, Any] =sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) a__ : int =sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6 ) def _A ( SCREAMING_SNAKE_CASE : numpy.ndarray ): """simple docstring""" return 1 / (1 + numpy.exp(-value )) def _A ( SCREAMING_SNAKE_CASE : numpy.ndarray ): """simple docstring""" return (value) * (1 - (value)) def _A ( ): """simple docstring""" a__ : List[Any] =numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) , dtype=numpy.floataa , ) # True output values for the given input values. a__ : Dict =numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa ) # Calling neural network class. a__ : Dict =TwoHiddenLayerNeuralNetwork( input_array=SCREAMING_SNAKE_CASE , output_array=SCREAMING_SNAKE_CASE ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=SCREAMING_SNAKE_CASE , iterations=10 , give_loss=SCREAMING_SNAKE_CASE ) return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) ) if __name__ == "__main__": example()
95
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 MobileViTImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] =size if size is not None else {"shortest_edge": 2_0} a__ : List[str] =crop_size if crop_size is not None else {"height": 1_8, "width": 1_8} a__ : Tuple =parent a__ : Union[str, Any] =batch_size a__ : List[str] =num_channels a__ : List[Any] =image_size a__ : str =min_resolution a__ : Optional[int] =max_resolution a__ : Tuple =do_resize a__ : Union[str, Any] =size a__ : List[Any] =do_center_crop a__ : List[str] =crop_size a__ : Optional[int] =do_flip_channel_order def _lowercase ( self ) -> Optional[int]: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : int = MobileViTImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : Tuple =MobileViTImageProcessingTester(self ) @property def _lowercase ( self ) -> List[str]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : str =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_flip_channel_order" ) ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : List[Any] =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 2_0} ) self.assertEqual(image_processor.crop_size , {"height": 1_8, "width": 1_8} ) a__ : Union[str, Any] =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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' pass def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : 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 a__ : List[Any] =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : List[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input a__ : 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 a__ : int =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : int =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input a__ : List[str] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a__ : List[str] =image_processing(lowerCAmelCase__ , 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"], ) , )
95
1
from __future__ import annotations from random import choice def _A ( SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" return choice(SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : list[int] , SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : List[str] =random_pivot(SCREAMING_SNAKE_CASE ) # partition based on pivot # linear time a__ : Tuple =[e for e in lst if e < pivot] a__ : Dict =[e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(SCREAMING_SNAKE_CASE ) == k - 1: return pivot # pivot is in elements bigger than k elif len(SCREAMING_SNAKE_CASE ) < k - 1: return kth_number(SCREAMING_SNAKE_CASE , k - len(SCREAMING_SNAKE_CASE ) - 1 ) # pivot is in elements smaller than k else: return kth_number(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
95
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 MobileNetVaImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=None , ) -> Optional[int]: '''simple docstring''' a__ : str =size if size is not None else {"shortest_edge": 2_0} a__ : Union[str, Any] =crop_size if crop_size is not None else {"height": 1_8, "width": 1_8} a__ : Tuple =parent a__ : Optional[int] =batch_size a__ : Any =num_channels a__ : List[str] =image_size a__ : Dict =min_resolution a__ : List[Any] =max_resolution a__ : Dict =do_resize a__ : Union[str, Any] =size a__ : str =do_center_crop a__ : List[str] =crop_size def _lowercase ( self ) -> str: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : Optional[Any] = MobileNetVaImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =MobileNetVaImageProcessingTester(self ) @property def _lowercase ( self ) -> List[str]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "crop_size" ) ) def _lowercase ( self ) -> str: '''simple docstring''' a__ : Any =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 2_0} ) self.assertEqual(image_processor.crop_size , {"height": 1_8, "width": 1_8} ) a__ : Dict =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 _lowercase ( self ) -> Any: '''simple docstring''' pass def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Dict =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : Optional[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : List[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 a__ : Dict =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> int: '''simple docstring''' a__ : str =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input a__ : List[str] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a__ : Union[str, Any] =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : int =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input a__ : Optional[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 a__ : str =image_processing(lowerCAmelCase__ , 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"], ) , )
95
1
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : int = logging.get_logger(__name__) UpperCAmelCase : List[str] = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : int = """conditional_detr""" _lowercase : int = ["""past_key_values"""] _lowercase : str = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=3 , lowerCAmelCase__=3_0_0 , lowerCAmelCase__=6 , lowerCAmelCase__=2_0_4_8 , lowerCAmelCase__=8 , lowerCAmelCase__=6 , lowerCAmelCase__=2_0_4_8 , lowerCAmelCase__=8 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=True , lowerCAmelCase__="relu" , lowerCAmelCase__=2_5_6 , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1.0 , lowerCAmelCase__=False , lowerCAmelCase__="sine" , lowerCAmelCase__="resnet50" , lowerCAmelCase__=True , lowerCAmelCase__=False , lowerCAmelCase__=2 , lowerCAmelCase__=5 , lowerCAmelCase__=2 , lowerCAmelCase__=1 , lowerCAmelCase__=1 , lowerCAmelCase__=2 , lowerCAmelCase__=5 , lowerCAmelCase__=2 , lowerCAmelCase__=0.25 , **lowerCAmelCase__ , ) -> List[str]: '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`." ) if not use_timm_backbone: if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) a__ : int =CONFIG_MAPPING["resnet"](out_features=["stage4"] ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Tuple =backbone_config.get("model_type" ) a__ : Dict =CONFIG_MAPPING[backbone_model_type] a__ : str =config_class.from_dict(lowerCAmelCase__ ) a__ : Optional[int] =use_timm_backbone a__ : str =backbone_config a__ : Any =num_channels a__ : List[Any] =num_queries a__ : Optional[Any] =d_model a__ : Optional[Any] =encoder_ffn_dim a__ : int =encoder_layers a__ : int =encoder_attention_heads a__ : Union[str, Any] =decoder_ffn_dim a__ : int =decoder_layers a__ : Optional[int] =decoder_attention_heads a__ : Optional[Any] =dropout a__ : Tuple =attention_dropout a__ : Tuple =activation_dropout a__ : Optional[int] =activation_function a__ : Tuple =init_std a__ : Optional[int] =init_xavier_std a__ : Optional[int] =encoder_layerdrop a__ : Dict =decoder_layerdrop a__ : Optional[int] =encoder_layers a__ : Any =auxiliary_loss a__ : Dict =position_embedding_type a__ : int =backbone a__ : Dict =use_pretrained_backbone a__ : Any =dilation # Hungarian matcher a__ : Optional[int] =class_cost a__ : Dict =bbox_cost a__ : Optional[int] =giou_cost # Loss coefficients a__ : Tuple =mask_loss_coefficient a__ : Any =dice_loss_coefficient a__ : Optional[Any] =cls_loss_coefficient a__ : Any =bbox_loss_coefficient a__ : Optional[Any] =giou_loss_coefficient a__ : str =focal_alpha super().__init__(is_encoder_decoder=lowerCAmelCase__ , **lowerCAmelCase__ ) @property def _lowercase ( self ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def _lowercase ( self ) -> int: '''simple docstring''' return self.d_model def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a__ : Tuple =self.backbone_config.to_dict() a__ : List[Any] =self.__class__.model_type return output class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Any = version.parse("""1.11""") @property def _lowercase ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("pixel_mask", {0: "batch"}), ] ) @property def _lowercase ( self ) -> float: '''simple docstring''' return 1E-5 @property def _lowercase ( self ) -> int: '''simple docstring''' return 1_2
95
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Any = { """configuration_convbert""": ["""CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvBertConfig""", """ConvBertOnnxConfig"""], """tokenization_convbert""": ["""ConvBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] = ["""ConvBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[str] = [ """CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConvBertForMaskedLM""", """ConvBertForMultipleChoice""", """ConvBertForQuestionAnswering""", """ConvBertForSequenceClassification""", """ConvBertForTokenClassification""", """ConvBertLayer""", """ConvBertModel""", """ConvBertPreTrainedModel""", """load_tf_weights_in_convbert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ """TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFConvBertForMaskedLM""", """TFConvBertForMultipleChoice""", """TFConvBertForQuestionAnswering""", """TFConvBertForSequenceClassification""", """TFConvBertForTokenClassification""", """TFConvBertLayer""", """TFConvBertModel""", """TFConvBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
95
1
import os import pytest from transformers.dynamic_module_utils import get_imports UpperCAmelCase : Optional[int] = """ import os """ UpperCAmelCase : List[str] = """ def foo(): import os return False """ UpperCAmelCase : Dict = """ def foo(): def bar(): if True: import os return False return bar() """ UpperCAmelCase : Dict = """ import os try: import bar except ImportError: raise ValueError() """ UpperCAmelCase : str = """ import os def foo(): try: import bar except ImportError: raise ValueError() """ UpperCAmelCase : Any = """ import os try: import bar except (ImportError, AttributeError): raise ValueError() """ UpperCAmelCase : List[Any] = """ import os try: import bar except ImportError as e: raise ValueError() """ UpperCAmelCase : Any = """ import os try: import bar except: raise ValueError() """ UpperCAmelCase : int = """ import os try: import bar import baz except ImportError: raise ValueError() """ UpperCAmelCase : List[Any] = """ import os try: import bar import baz except ImportError: x = 1 raise ValueError() """ UpperCAmelCase : List[Any] = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize("case" , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" a__ : int =os.path.join(SCREAMING_SNAKE_CASE , "test_file.py" ) with open(SCREAMING_SNAKE_CASE , "w" ) as _tmp_file: _tmp_file.write(SCREAMING_SNAKE_CASE ) a__ : List[str] =get_imports(SCREAMING_SNAKE_CASE ) assert parsed_imports == ["os"]
95
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : Tuple = { """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Any = """swin2sr""" _lowercase : Tuple = { """hidden_size""": """embed_dim""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , lowerCAmelCase__=6_4 , lowerCAmelCase__=1 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8_0 , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=8 , lowerCAmelCase__=2.0 , lowerCAmelCase__=True , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__="gelu" , lowerCAmelCase__=False , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-5 , lowerCAmelCase__=2 , lowerCAmelCase__=1.0 , lowerCAmelCase__="1conv" , lowerCAmelCase__="pixelshuffle" , **lowerCAmelCase__ , ) -> int: '''simple docstring''' super().__init__(**lowerCAmelCase__ ) a__ : Optional[Any] =image_size a__ : Dict =patch_size a__ : Tuple =num_channels a__ : Union[str, Any] =embed_dim a__ : Optional[Any] =depths a__ : List[str] =len(lowerCAmelCase__ ) a__ : Any =num_heads a__ : Any =window_size a__ : str =mlp_ratio a__ : List[str] =qkv_bias a__ : Dict =hidden_dropout_prob a__ : List[str] =attention_probs_dropout_prob a__ : Dict =drop_path_rate a__ : Optional[Any] =hidden_act a__ : Union[str, Any] =use_absolute_embeddings a__ : Optional[Any] =layer_norm_eps a__ : List[Any] =initializer_range a__ : int =upscale a__ : Optional[int] =img_range a__ : Any =resi_connection a__ : Optional[Any] =upsampler
95
1
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Optional[Any] =2 a__ : Dict =[] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(SCREAMING_SNAKE_CASE ) if n > 1: factors.append(SCREAMING_SNAKE_CASE ) return factors if __name__ == "__main__": import doctest doctest.testmod()
95
from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class __lowerCAmelCase : pass
95
1
from collections.abc import Generator from math import sin def _A ( SCREAMING_SNAKE_CASE : bytes ): """simple docstring""" if len(SCREAMING_SNAKE_CASE ) != 32: raise ValueError("Input must be of length 32" ) a__ : Optional[Any] =b"" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" if i < 0: raise ValueError("Input must be non-negative" ) a__ : Optional[Any] =format(SCREAMING_SNAKE_CASE , "08x" )[-8:] a__ : Tuple =b"" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8" ) return little_endian_hex def _A ( SCREAMING_SNAKE_CASE : bytes ): """simple docstring""" a__ : Any =b"" for char in message: bit_string += format(SCREAMING_SNAKE_CASE , "08b" ).encode("utf-8" ) a__ : Optional[Any] =format(len(SCREAMING_SNAKE_CASE ) , "064b" ).encode("utf-8" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(SCREAMING_SNAKE_CASE ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def _A ( SCREAMING_SNAKE_CASE : bytes ): """simple docstring""" if len(SCREAMING_SNAKE_CASE ) % 512 != 0: raise ValueError("Input must have length that's a multiple of 512" ) for pos in range(0 , len(SCREAMING_SNAKE_CASE ) , 512 ): a__ : List[str] =bit_string[pos : pos + 512] a__ : Union[str, Any] =[] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" if i < 0: raise ValueError("Input must be non-negative" ) a__ : Optional[int] =format(SCREAMING_SNAKE_CASE , "032b" ) a__ : Optional[int] ="" for c in i_str: new_str += "1" if c == "0" else "0" return int(SCREAMING_SNAKE_CASE , 2 ) def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return (a + b) % 2**32 def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" if i < 0: raise ValueError("Input must be non-negative" ) if shift < 0: raise ValueError("Shift must be non-negative" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def _A ( SCREAMING_SNAKE_CASE : bytes ): """simple docstring""" a__ : str =preprocess(SCREAMING_SNAKE_CASE ) a__ : List[str] =[int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states a__ : List[Any] =0x67_452_301 a__ : Optional[Any] =0xEF_CDA_B89 a__ : List[Any] =0x98_BAD_CFE a__ : Any =0x10_325_476 a__ : str =[ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(SCREAMING_SNAKE_CASE ): a__ : List[Any] =aa a__ : List[Any] =ba a__ : List[Any] =ca a__ : List[str] =da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f a__ : Tuple =d ^ (b & (c ^ d)) a__ : str =i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f a__ : Any =c ^ (d & (b ^ c)) a__ : str =(5 * i + 1) % 16 elif i <= 47: a__ : Dict =b ^ c ^ d a__ : Optional[Any] =(3 * i + 5) % 16 else: a__ : Optional[Any] =c ^ (b | not_aa(SCREAMING_SNAKE_CASE )) a__ : str =(7 * i) % 16 a__ : Optional[Any] =(f + a + added_consts[i] + block_words[g]) % 2**32 a__ : List[Any] =d a__ : List[str] =c a__ : int =b a__ : Dict =sum_aa(SCREAMING_SNAKE_CASE , left_rotate_aa(SCREAMING_SNAKE_CASE , shift_amounts[i] ) ) # Add hashed chunk to running total a__ : Union[str, Any] =sum_aa(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : List[Any] =sum_aa(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : int =sum_aa(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : List[str] =sum_aa(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Tuple =reformat_hex(SCREAMING_SNAKE_CASE ) + reformat_hex(SCREAMING_SNAKE_CASE ) + reformat_hex(SCREAMING_SNAKE_CASE ) + reformat_hex(SCREAMING_SNAKE_CASE ) return digest if __name__ == "__main__": import doctest doctest.testmod()
95
# 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 __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = """philschmid/bart-large-cnn-samsum""" _lowercase : List[Any] = ( """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.""" ) _lowercase : Any = """summarizer""" _lowercase : Any = AutoTokenizer _lowercase : str = AutoModelForSeqaSeqLM _lowercase : Optional[int] = ["""text"""] _lowercase : Optional[int] = ["""text"""] def _lowercase ( self , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' return self.pre_processor(lowerCAmelCase__ , return_tensors="pt" , truncation=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return self.model.generate(**lowerCAmelCase__ )[0] def _lowercase ( self , lowerCAmelCase__ ) -> Any: '''simple docstring''' return self.pre_processor.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ )
95
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType UpperCAmelCase : Any = logging.get_logger(__name__) UpperCAmelCase : List[str] = { """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""", } # fmt: off UpperCAmelCase : Optional[Any] = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377, 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211, 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786, 11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791, 17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409, 34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361 ] UpperCAmelCase : Tuple = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627, 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647, 7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793, 14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675, 22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865, 42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362 ] class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[str] = """whisper""" _lowercase : List[Any] = ["""past_key_values"""] _lowercase : str = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCAmelCase__=5_1_8_6_5 , lowerCAmelCase__=8_0 , lowerCAmelCase__=6 , lowerCAmelCase__=4 , lowerCAmelCase__=6 , lowerCAmelCase__=4 , lowerCAmelCase__=1_5_3_6 , lowerCAmelCase__=1_5_3_6 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=5_0_2_5_7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__="gelu" , lowerCAmelCase__=2_5_6 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.02 , lowerCAmelCase__=False , lowerCAmelCase__=1_5_0_0 , lowerCAmelCase__=4_4_8 , lowerCAmelCase__=5_0_2_5_6 , lowerCAmelCase__=5_0_2_5_6 , lowerCAmelCase__=5_0_2_5_6 , lowerCAmelCase__=None , lowerCAmelCase__=[2_2_0, 5_0_2_5_6] , lowerCAmelCase__=False , lowerCAmelCase__=2_5_6 , lowerCAmelCase__=False , lowerCAmelCase__=0.05 , lowerCAmelCase__=1_0 , lowerCAmelCase__=2 , lowerCAmelCase__=0.0 , lowerCAmelCase__=1_0 , lowerCAmelCase__=0 , lowerCAmelCase__=7 , **lowerCAmelCase__ , ) -> Any: '''simple docstring''' a__ : Optional[Any] =vocab_size a__ : List[str] =num_mel_bins a__ : List[str] =d_model a__ : Optional[Any] =encoder_layers a__ : Union[str, Any] =encoder_attention_heads a__ : List[Any] =decoder_layers a__ : Dict =decoder_attention_heads a__ : str =decoder_ffn_dim a__ : int =encoder_ffn_dim a__ : Tuple =dropout a__ : Optional[Any] =attention_dropout a__ : List[str] =activation_dropout a__ : str =activation_function a__ : Dict =init_std a__ : List[str] =encoder_layerdrop a__ : Optional[Any] =decoder_layerdrop a__ : Optional[Any] =use_cache a__ : Tuple =encoder_layers a__ : int =scale_embedding # scale factor will be sqrt(d_model) if True a__ : Union[str, Any] =max_source_positions a__ : Union[str, Any] =max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. a__ : List[Any] =classifier_proj_size a__ : int =use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 a__ : str =apply_spec_augment a__ : Union[str, Any] =mask_time_prob a__ : Dict =mask_time_length a__ : int =mask_time_min_masks a__ : Optional[int] =mask_feature_prob a__ : List[Any] =mask_feature_length a__ : Tuple =mask_feature_min_masks a__ : List[str] =median_filter_width super().__init__( pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , is_encoder_decoder=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , suppress_tokens=lowerCAmelCase__ , begin_suppress_tokens=lowerCAmelCase__ , **lowerCAmelCase__ , ) class __lowerCAmelCase ( UpperCamelCase__): @property def _lowercase ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' a__ : List[str] =OrderedDict( [ ("input_features", {0: "batch", 1: "feature_size", 2: "encoder_sequence"}), ] ) if self.use_past: a__ : str ={0: "batch"} else: a__ : List[str] ={0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(lowerCAmelCase__ , direction="inputs" ) return common_inputs def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = -1 , lowerCAmelCase__ = -1 , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = 2_2_0_5_0 , lowerCAmelCase__ = 5.0 , lowerCAmelCase__ = 2_2_0 , ) -> Mapping[str, Any]: '''simple docstring''' a__ : str =OrderedDict() a__ : Optional[int] =OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=lowerCAmelCase__ , framework=lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , time_duration=lowerCAmelCase__ , frequency=lowerCAmelCase__ , ) a__ : Optional[Any] =encoder_inputs["input_features"].shape[2] a__ : Dict =encoder_sequence_length // 2 if self.use_past else seq_length a__ : List[str] =super().generate_dummy_inputs( preprocessor.tokenizer , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) a__ : Optional[Any] =encoder_inputs.pop("input_features" ) a__ : Optional[Any] =decoder_inputs.pop("decoder_input_ids" ) if "past_key_values" in decoder_inputs: a__ : List[Any] =decoder_inputs.pop("past_key_values" ) return dummy_inputs @property def _lowercase ( self ) -> float: '''simple docstring''' return 1E-3
95
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer UpperCAmelCase : int = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase : List[Any] = [ """small""", """small-base""", """medium""", """medium-base""", """intermediate""", """intermediate-base""", """large""", """large-base""", """xlarge""", """xlarge-base""", ] UpperCAmelCase : Optional[int] = { """vocab_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt""", """funnel-transformer/small-base""": """https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt""", """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt""", """funnel-transformer/large-base""": """https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt""", """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json""", """funnel-transformer/small-base""": ( """https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json""" ), """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json""", """funnel-transformer/large-base""": ( """https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json""" ), """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json""" ), }, } UpperCAmelCase : Optional[int] = {F"""funnel-transformer/{name}""": 512 for name in _model_names} UpperCAmelCase : Optional[int] = {F"""funnel-transformer/{name}""": {"""do_lower_case""": True} for name in _model_names} class __lowerCAmelCase ( UpperCamelCase__): _lowercase : str = VOCAB_FILES_NAMES _lowercase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowercase : Dict = PRETRAINED_INIT_CONFIGURATION _lowercase : Union[str, Any] = FunnelTokenizer _lowercase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : int = 2 def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<sep>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="<cls>" , lowerCAmelCase__="<mask>" , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__="##" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , clean_text=lowerCAmelCase__ , tokenize_chinese_chars=lowerCAmelCase__ , strip_accents=lowerCAmelCase__ , wordpieces_prefix=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : Optional[Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowerCAmelCase__ ) != do_lower_case or normalizer_state.get("strip_accents" , lowerCAmelCase__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowerCAmelCase__ ) != tokenize_chinese_chars ): a__ : List[str] =getattr(lowerCAmelCase__ , normalizer_state.pop("type" ) ) a__ : Union[str, Any] =do_lower_case a__ : Any =strip_accents a__ : Optional[Any] =tokenize_chinese_chars a__ : Dict =normalizer_class(**lowerCAmelCase__ ) a__ : Any =do_lower_case def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> str: '''simple docstring''' a__ : Dict =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] =[self.sep_token_id] a__ : Union[str, Any] =[self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: '''simple docstring''' a__ : Tuple =self._tokenizer.model.save(lowerCAmelCase__ , name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ )
95
1
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys UpperCAmelCase : Optional[Any] = subprocess.check_output("""git merge-base main HEAD""".split()).decode("""utf-8""") UpperCAmelCase : Optional[Any] = subprocess.check_output(F"""git diff --name-only {fork_point_sha}""".split()).decode("""utf-8""").split() UpperCAmelCase : Dict = """|""".join(sys.argv[1:]) UpperCAmelCase : Optional[Any] = re.compile(rF"""^({joined_dirs}).*?\.py$""") UpperCAmelCase : List[str] = [x for x in modified_files if regex.match(x)] print(""" """.join(relevant_modified_files), end="""""")
95
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 ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = "arrow" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( split=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ , streaming=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : int =load_from_cache_file a__ : Tuple =file_format a__ : List[Any] =Spark( df=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , working_dir=lowerCAmelCase__ , **lowerCAmelCase__ , ) def _lowercase ( self ) -> str: '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) a__ : str =None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowerCAmelCase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
95
1
import functools from typing import Any def _A ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : list[str] ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("the string should be not empty string" ) if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or not all( isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) > 0 for item in words ): raise ValueError("the words should be a list of non-empty strings" ) # Build trie a__ : dict[str, Any] ={} a__ : List[Any] ="WORD_KEEPER" for word in words: a__ : Union[str, Any] =trie for c in word: if c not in trie_node: a__ : Optional[Any] ={} a__ : str =trie_node[c] a__ : str =True a__ : Any =len(SCREAMING_SNAKE_CASE ) # Dynamic programming method @functools.cache def is_breakable(SCREAMING_SNAKE_CASE : int ) -> bool: if index == len_string: return True a__ : Union[str, Any] =trie for i in range(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): a__ : Union[str, Any] =trie_node.get(string[i] , SCREAMING_SNAKE_CASE ) if trie_node is None: return False if trie_node.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
95
from math import pi def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
95
1
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 __lowerCAmelCase ( enum.Enum): _lowercase : Any = 0 _lowercase : str = 1 _lowercase : str = 2 @add_end_docstrings(UpperCamelCase__) class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Dict = """ 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 , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__ ) 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. a__ : Optional[Any] =None if self.model.config.prefix is not None: a__ : str =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. a__ : Any =self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. a__ , a__ , a__ : Tuple =self._sanitize_parameters(prefix=lowerCAmelCase__ , **self._forward_params ) a__ : List[str] ={**self._preprocess_params, **preprocess_params} a__ : Tuple ={**self._forward_params, **forward_params} def _lowercase ( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None , **lowerCAmelCase__ , ) -> Tuple: '''simple docstring''' a__ : Tuple ={} if prefix is not None: a__ : Optional[Any] =prefix if prefix: a__ : Optional[Any] =self.tokenizer( lowerCAmelCase__ , padding=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_tensors=self.framework ) a__ : str =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']" ) a__ : List[Any] =handle_long_generation preprocess_params.update(lowerCAmelCase__ ) a__ : Tuple =generate_kwargs a__ : Union[str, Any] ={} 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`" ) a__ : str =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`" ) a__ : Any =ReturnType.TENSORS if return_type is not None: a__ : Dict =return_type if clean_up_tokenization_spaces is not None: a__ : int =clean_up_tokenization_spaces if stop_sequence is not None: a__ : Optional[int] =self.tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) if len(lowerCAmelCase__ ) > 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." ) a__ : Optional[Any] =stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _lowercase ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> int: '''simple docstring''' if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"add_space_before_punct_symbol": True} ) return super()._parse_and_tokenize(*lowerCAmelCase__ , **lowerCAmelCase__ ) def __call__( self , lowerCAmelCase__ , **lowerCAmelCase__ ) -> Any: '''simple docstring''' return super().__call__(lowerCAmelCase__ , **lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__="" , lowerCAmelCase__=None , **lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' a__ : Optional[Any] =self.tokenizer( prefix + prompt_text , padding=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_tensors=self.framework ) a__ : Optional[Any] =prompt_text if handle_long_generation == "hole": a__ : Tuple =inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: a__ : List[str] =generate_kwargs["max_new_tokens"] else: a__ : Dict =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: a__ : Optional[Any] =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" ) a__ : Tuple =inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: a__ : List[Any] =inputs["attention_mask"][:, -keep_length:] return inputs def _lowercase ( self , lowerCAmelCase__ , **lowerCAmelCase__ ) -> List[str]: '''simple docstring''' a__ : Optional[int] =model_inputs["input_ids"] a__ : Optional[Any] =model_inputs.get("attention_mask" , lowerCAmelCase__ ) # Allow empty prompts if input_ids.shape[1] == 0: a__ : Tuple =None a__ : Tuple =None a__ : Dict =1 else: a__ : List[str] =input_ids.shape[0] a__ : Any =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. a__ : List[Any] =generate_kwargs.pop("prefix_length" , 0 ) if prefix_length > 0: a__ : Any ="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: a__ : Any =generate_kwargs.get("max_length" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length a__ : List[Any] ="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 a__ : Union[str, Any] =self.model.generate(input_ids=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : str =generated_sequence.shape[0] if self.framework == "pt": a__ : Any =generated_sequence.reshape(lowerCAmelCase__ , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": a__ : Tuple =tf.reshape(lowerCAmelCase__ , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=ReturnType.FULL_TEXT , lowerCAmelCase__=True ) -> Union[str, Any]: '''simple docstring''' a__ : str =model_outputs["generated_sequence"][0] a__ : Dict =model_outputs["input_ids"] a__ : Optional[int] =model_outputs["prompt_text"] a__ : str =generated_sequence.numpy().tolist() a__ : Any =[] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: a__ : str ={"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text a__ : List[Any] =self.tokenizer.decode( lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: a__ : int =0 else: a__ : Any =len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ , ) ) if return_type == ReturnType.FULL_TEXT: a__ : str =prompt_text + text[prompt_length:] else: a__ : Union[str, Any] =text[prompt_length:] a__ : str ={"generated_text": all_text} records.append(lowerCAmelCase__ ) return records
95
import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging UpperCAmelCase : int = { """cola""": 2, """mnli""": 3, """mrpc""": 2, """sst-2""": 2, """sts-b""": 1, """qqp""": 2, """qnli""": 2, """rte""": 2, """wnli""": 2, } logging.set_verbosity_info() def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any]=None ): """simple docstring""" a__ : Optional[int] =XLNetConfig.from_json_file(SCREAMING_SNAKE_CASE ) a__ : Dict =finetuning_task.lower() if finetuning_task is not None else "" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(f'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}''' ) a__ : List[str] =finetuning_task a__ : Tuple =GLUE_TASKS_NUM_LABELS[finetuning_task] a__ : List[Any] =XLNetForSequenceClassification(SCREAMING_SNAKE_CASE ) elif "squad" in finetuning_task: a__ : Optional[int] =finetuning_task a__ : Dict =XLNetForQuestionAnswering(SCREAMING_SNAKE_CASE ) else: a__ : List[Any] =XLNetLMHeadModel(SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Save pytorch-model a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print(f'''Save PyTorch model to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE ) print(f'''Save configuration file to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--xlnet_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained XLNet model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the folder to store the PyTorch model or dataset/vocab.""", ) parser.add_argument( """--finetuning_task""", default=None, type=str, help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""", ) UpperCAmelCase : int = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
95
1
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def _A ( SCREAMING_SNAKE_CASE : Namespace ): """simple docstring""" return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) UpperCAmelCase : Optional[int] = """ transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions. """ class __lowerCAmelCase ( UpperCamelCase__): @staticmethod def _lowercase ( lowerCAmelCase__ ) -> Any: '''simple docstring''' a__ : int =parser.add_parser( "convert" , help="CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints." , ) train_parser.add_argument("--model_type" , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="Model's type." ) train_parser.add_argument( "--tf_checkpoint" , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="TensorFlow checkpoint path or folder." ) train_parser.add_argument( "--pytorch_dump_output" , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="Path to the PyTorch saved model output." ) train_parser.add_argument("--config" , type=lowerCAmelCase__ , default="" , help="Configuration file path or folder." ) train_parser.add_argument( "--finetuning_task_name" , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help="Optional fine-tuning task name if the TF model was a finetuned model." , ) train_parser.set_defaults(func=lowerCAmelCase__ ) def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' a__ : Optional[int] =logging.get_logger("transformers-cli/converting" ) self._logger.info(F'''Loading model {model_type}''' ) a__ : Optional[int] =model_type a__ : Union[str, Any] =tf_checkpoint a__ : Optional[Any] =pytorch_dump_output a__ : Dict =config a__ : Tuple =finetuning_task_name def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(lowerCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase__ ) if "ckpt" in self._tf_checkpoint.lower(): a__ : Tuple =self._tf_checkpoint a__ : str ="" else: a__ : Union[str, Any] =self._tf_checkpoint a__ : List[Any] ="" convert_transfo_xl_checkpoint_to_pytorch( lowerCAmelCase__ , self._config , self._pytorch_dump_output , lowerCAmelCase__ ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase__ ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCAmelCase__ ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( "--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]" )
95
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { """google/canine-s""": """https://huggingface.co/google/canine-s/resolve/main/config.json""", # See all CANINE models at https://huggingface.co/models?filter=canine } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[Any] = """canine""" def __init__( self , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_6 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=0 , lowerCAmelCase__=0XE0_00 , lowerCAmelCase__=0XE0_01 , lowerCAmelCase__=4 , lowerCAmelCase__=4 , lowerCAmelCase__=8 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_2_8 , **lowerCAmelCase__ , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Optional[int] =max_position_embeddings a__ : str =hidden_size a__ : Optional[Any] =num_hidden_layers a__ : Tuple =num_attention_heads a__ : Optional[Any] =intermediate_size a__ : Optional[int] =hidden_act a__ : List[Any] =hidden_dropout_prob a__ : Union[str, Any] =attention_probs_dropout_prob a__ : Optional[Any] =initializer_range a__ : Union[str, Any] =type_vocab_size a__ : Optional[int] =layer_norm_eps # Character config: a__ : int =downsampling_rate a__ : Optional[Any] =upsampling_kernel_size a__ : Union[str, Any] =num_hash_functions a__ : Any =num_hash_buckets a__ : int =local_transformer_stride
95
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 __lowerCAmelCase : def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=3 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__=9_9 , lowerCAmelCase__=3_2 , lowerCAmelCase__=5 , lowerCAmelCase__=4 , lowerCAmelCase__=3_7 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=1_6 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=None , ) -> List[Any]: '''simple docstring''' a__ : Optional[Any] =parent a__ : Tuple =batch_size a__ : int =seq_length a__ : Tuple =is_training a__ : Any =use_input_mask a__ : Optional[int] =use_token_type_ids a__ : List[str] =use_labels a__ : Optional[Any] =vocab_size a__ : Dict =hidden_size a__ : List[Any] =num_hidden_layers a__ : List[Any] =num_attention_heads a__ : Union[str, Any] =intermediate_size a__ : Tuple =hidden_act a__ : Dict =hidden_dropout_prob a__ : Any =attention_probs_dropout_prob a__ : Tuple =max_position_embeddings a__ : Optional[int] =type_vocab_size a__ : Any =type_sequence_label_size a__ : Optional[int] =initializer_range a__ : Optional[Any] =num_labels a__ : int =num_choices a__ : Optional[int] =scope def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : int =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : int =None if self.use_input_mask: a__ : Dict =random_attention_mask([self.batch_size, self.seq_length] ) a__ : Any =None a__ : Optional[Any] =None a__ : Tuple =None a__ : Dict =None if self.use_labels: a__ : str =ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : Tuple =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a__ : str =ids_tensor([self.batch_size] , self.num_choices ) a__ : Union[str, Any] =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self ) -> str: '''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=lowerCAmelCase__ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=lowerCAmelCase__ , ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' a__ : List[Any] =FalconModel(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : List[str] =model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ ) a__ : str =model(lowerCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> Any: '''simple docstring''' a__ : List[Any] =True a__ : Any =FalconModel(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : int =model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , encoder_hidden_states=lowerCAmelCase__ , encoder_attention_mask=lowerCAmelCase__ , ) a__ : int =model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , encoder_hidden_states=lowerCAmelCase__ , ) a__ : Any =model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> Union[str, Any]: '''simple docstring''' a__ : Any =FalconForCausalLM(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : Tuple =model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> Dict: '''simple docstring''' a__ : str =True a__ : Union[str, Any] =True a__ : str =FalconForCausalLM(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() # first forward pass a__ : int =model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , encoder_hidden_states=lowerCAmelCase__ , encoder_attention_mask=lowerCAmelCase__ , use_cache=lowerCAmelCase__ , ) a__ : str =outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids a__ : Union[str, Any] =ids_tensor((self.batch_size, 3) , config.vocab_size ) a__ : List[Any] =ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and a__ : Union[str, Any] =torch.cat([input_ids, next_tokens] , dim=-1 ) a__ : Tuple =torch.cat([input_mask, next_mask] , dim=-1 ) a__ : str =model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , encoder_hidden_states=lowerCAmelCase__ , encoder_attention_mask=lowerCAmelCase__ , output_hidden_states=lowerCAmelCase__ , )["hidden_states"][0] a__ : Tuple =model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , encoder_hidden_states=lowerCAmelCase__ , encoder_attention_mask=lowerCAmelCase__ , past_key_values=lowerCAmelCase__ , output_hidden_states=lowerCAmelCase__ , )["hidden_states"][0] # select random slice a__ : int =ids_tensor((1,) , output_from_past.shape[-1] ).item() a__ : List[Any] =output_from_no_past[:, -3:, random_slice_idx].detach() a__ : Tuple =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Dict =self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ) : Tuple =config_and_inputs a__ : Optional[Any] ={"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase): _lowercase : int = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) _lowercase : Any = (FalconForCausalLM,) if is_torch_available() else () _lowercase : int = ( { """feature-extraction""": FalconModel, """text-classification""": FalconForSequenceClassification, """text-generation""": FalconForCausalLM, """question-answering""": FalconForQuestionAnswering, """token-classification""": FalconForTokenClassification, """zero-shot""": FalconForSequenceClassification, } if is_torch_available() else {} ) _lowercase : Dict = False _lowercase : int = False def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : str =FalconModelTester(self ) a__ : Any =ConfigTester(self , config_class=lowerCAmelCase__ , hidden_size=3_7 ) def _lowercase ( self ) -> Dict: '''simple docstring''' self.config_tester.run_common_tests() def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase__ ) def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ , *a__ : Dict =self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: a__ : Any =alibi self.model_tester.create_and_check_model(lowerCAmelCase__ , *lowerCAmelCase__ ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ , a__ : List[str] =self.model_tester.prepare_config_and_inputs_for_common() a__ : List[str] =3 a__ : List[Any] =input_dict["input_ids"] a__ : Tuple =input_ids.ne(1 ).to(lowerCAmelCase__ ) a__ : Optional[int] =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) a__ : Tuple =FalconForSequenceClassification(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : Optional[Any] =model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _lowercase ( self ) -> int: '''simple docstring''' a__ , a__ : int =self.model_tester.prepare_config_and_inputs_for_common() a__ : Optional[Any] =3 a__ : Dict ="single_label_classification" a__ : Optional[int] =input_dict["input_ids"] a__ : Any =input_ids.ne(1 ).to(lowerCAmelCase__ ) a__ : Optional[Any] =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) a__ : Dict =FalconForSequenceClassification(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : Optional[int] =model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ , a__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() a__ : str =input_dict["input_ids"] a__ : Any =FalconForCausalLM(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : Union[str, Any] =model(lowerCAmelCase__ , use_cache=lowerCAmelCase__ ) a__ : Union[str, Any] =input_ids.shape[0] a__ : Union[str, Any] =model._convert_to_rw_cache(result.past_key_values ) a__ : int =model._convert_cache_to_standard_format(lowerCAmelCase__ , lowerCAmelCase__ ) for layer in range(len(lowerCAmelCase__ ) ): 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 _lowercase ( self ) -> int: '''simple docstring''' a__ , a__ : List[str] =self.model_tester.prepare_config_and_inputs_for_common() a__ : List[str] =3 a__ : Union[str, Any] ="multi_label_classification" a__ : Optional[int] =input_dict["input_ids"] a__ : List[Any] =input_ids.ne(1 ).to(lowerCAmelCase__ ) a__ : Tuple =ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) a__ : Tuple =FalconForSequenceClassification(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : Tuple =model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' for model_class in self.all_generative_model_classes: a__ , a__ : int =self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(lowerCAmelCase__ , "use_cache" ): return a__ : int =model_class(lowerCAmelCase__ ).to(lowerCAmelCase__ ) if "use_cache" not in inputs: a__ : Optional[int] =True a__ : Dict =model(**lowerCAmelCase__ ) # 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__ : int =( getattr(lowerCAmelCase__ , "decoder_layers" , lowerCAmelCase__ ) or getattr(lowerCAmelCase__ , "num_decoder_layers" , lowerCAmelCase__ ) or config.num_hidden_layers ) a__ : str =getattr(lowerCAmelCase__ , "num_kv_heads" , config.num_attention_heads ) a__ : Tuple =getattr(lowerCAmelCase__ , "d_model" , config.hidden_size ) a__ : Any =embed_dim // num_attention_heads a__ : List[Any] =outputs["past_key_values"] self.assertEqual(len(lowerCAmelCase__ ) , lowerCAmelCase__ ) a__ , a__ : Tuple =inputs["input_ids"].shape for i in range(lowerCAmelCase__ ): if config.new_decoder_architecture: a__ : Dict =config.num_attention_heads elif config.multi_query: a__ : List[str] =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 __lowerCAmelCase ( unittest.TestCase): @slow def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : str =AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b" ) a__ : str =FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b" ) model.eval() model.to(lowerCAmelCase__ ) a__ : int =tokenizer("My favorite food is" , return_tensors="pt" ).to(lowerCAmelCase__ ) a__ : str =( "My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday." ) a__ : Tuple =model.generate(**lowerCAmelCase__ , do_sample=lowerCAmelCase__ , max_new_tokens=1_9 ) a__ : Tuple =tokenizer.batch_decode(lowerCAmelCase__ )[0] self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__ ) @slow def _lowercase ( self ) -> List[Any]: '''simple docstring''' for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: a__ : Union[str, Any] =AutoTokenizer.from_pretrained(lowerCAmelCase__ ) a__ : Any =FalconForCausalLM.from_pretrained(lowerCAmelCase__ ) model.eval() model.to(lowerCAmelCase__ ) a__ : Optional[int] =tokenizer("My favorite food is" , return_tensors="pt" ).to(lowerCAmelCase__ ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**lowerCAmelCase__ , do_sample=lowerCAmelCase__ , max_new_tokens=4 ) model.generate(**lowerCAmelCase__ , do_sample=lowerCAmelCase__ , max_new_tokens=4 ) model.generate(**lowerCAmelCase__ , num_beams=2 , max_new_tokens=4 ) @slow def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: a__ : str =AutoTokenizer.from_pretrained(lowerCAmelCase__ ) a__ : int =FalconForCausalLM.from_pretrained(lowerCAmelCase__ ) model.eval() model.to(device=lowerCAmelCase__ ) a__ : Optional[int] =tokenizer("My favorite food is" , return_tensors="pt" ).to(lowerCAmelCase__ ) # Test results are the same with and without cache a__ : Optional[int] =model.generate(**lowerCAmelCase__ , do_sample=lowerCAmelCase__ , max_new_tokens=2_0 , use_cache=lowerCAmelCase__ ) a__ : Any =model.generate(**lowerCAmelCase__ , do_sample=lowerCAmelCase__ , max_new_tokens=2_0 , use_cache=lowerCAmelCase__ ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
95
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device UpperCAmelCase : int = False class __lowerCAmelCase ( unittest.TestCase): pass @nightly @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Optional[Any] =torch.manual_seed(0 ) a__ : Optional[Any] =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCAmelCase__ ) a__ : str =VersatileDiffusionPipeline.from_pretrained(lowerCAmelCase__ , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] =generator.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] ="cyberpunk 2077" a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Union[str, Any] =torch.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images a__ : int =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : str ="A painting of a squirrel eating a burger " a__ : Optional[int] =torch.manual_seed(0 ) a__ : str =pipe.text_to_image( prompt=lowerCAmelCase__ , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" ).images a__ : Any =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Optional[int] =np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : Optional[Any] =pipe.image_variation(lowerCAmelCase__ , generator=lowerCAmelCase__ , output_type="numpy" ).images a__ : Union[str, Any] =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
95
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = logging.get_logger(__name__) UpperCAmelCase : str = { """post_extract_proj""": """feature_projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.upsample.0""": """encoder.upsample.projection""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str ): """simple docstring""" for attribute in key.split("." ): a__ : Tuple =getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if weight_type is not None: a__ : Any =getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).shape else: a__ : Optional[Any] =hf_pointer.shape assert hf_shape == value.shape, ( f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": a__ : int =value elif weight_type == "weight_g": a__ : Optional[Any] =value elif weight_type == "weight_v": a__ : int =value elif weight_type == "bias": a__ : Any =value else: a__ : Optional[int] =value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def _A ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" a__ : List[str] =[] a__ : Dict =fairseq_model.state_dict() a__ : Union[str, Any] =hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): a__ : Optional[Any] =False if "conv_layers" in name: load_conv_layer( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == "group" , ) a__ : List[str] =True else: for key, mapped_key in MAPPING.items(): a__ : str ="sew." + mapped_key if (is_finetuned and mapped_key != "lm_head") else mapped_key if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: a__ : Tuple =True if "*" in mapped_key: a__ : str =name.split(SCREAMING_SNAKE_CASE )[0].split("." )[-2] a__ : List[str] =mapped_key.replace("*" , SCREAMING_SNAKE_CASE ) if "weight_g" in name: a__ : List[str] ="weight_g" elif "weight_v" in name: a__ : Optional[int] ="weight_v" elif "weight" in name: a__ : Tuple ="weight" elif "bias" in name: a__ : Optional[int] ="bias" else: a__ : List[Any] =None set_recursively(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Any ): """simple docstring""" a__ : int =full_name.split("conv_layers." )[-1] a__ : Union[str, Any] =name.split("." ) a__ : Tuple =int(items[0] ) a__ : Any =int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) a__ : Any =value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) a__ : Any =value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) a__ : int =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) a__ : str =value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" a__ : Optional[int] =SEWConfig() if is_finetuned: a__ : Optional[Any] =model.wav_encoder.wav_model.cfg else: a__ : int =model.cfg a__ : Optional[Any] =fs_config.conv_bias a__ : List[Any] =eval(fs_config.conv_feature_layers ) a__ : Dict =[x[0] for x in conv_layers] a__ : str =[x[1] for x in conv_layers] a__ : Tuple =[x[2] for x in conv_layers] a__ : List[str] ="gelu" a__ : int ="layer" if fs_config.extractor_mode == "layer_norm" else "group" a__ : Optional[Any] =0.0 a__ : List[str] =fs_config.activation_fn.name a__ : Union[str, Any] =fs_config.encoder_embed_dim a__ : Any =0.0_2 a__ : Optional[Any] =fs_config.encoder_ffn_embed_dim a__ : Tuple =1e-5 a__ : Union[str, Any] =fs_config.encoder_layerdrop a__ : List[Any] =fs_config.encoder_attention_heads a__ : int =fs_config.conv_pos_groups a__ : int =fs_config.conv_pos a__ : Optional[Any] =len(SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =fs_config.encoder_layers a__ : Tuple =fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: a__ : Any =model.cfg a__ : Optional[Any] =fs_config.final_dropout a__ : Optional[int] =fs_config.layerdrop a__ : Optional[Any] =fs_config.activation_dropout a__ : Dict =fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 a__ : Tuple =fs_config.attention_dropout a__ : Tuple =fs_config.dropout_input a__ : List[str] =fs_config.dropout a__ : Optional[int] =fs_config.mask_channel_length a__ : List[str] =fs_config.mask_channel_prob a__ : Any =fs_config.mask_length a__ : Union[str, Any] =fs_config.mask_prob a__ : List[str] ="Wav2Vec2FeatureExtractor" a__ : List[str] ="Wav2Vec2CTCTokenizer" return config @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : str=None , SCREAMING_SNAKE_CASE : Dict=None , SCREAMING_SNAKE_CASE : List[str]=True ): """simple docstring""" if is_finetuned: a__ , a__ , a__ : Tuple =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) else: a__ , a__ , a__ : Dict =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: a__ : List[str] =SEWConfig.from_pretrained(SCREAMING_SNAKE_CASE ) else: a__ : Optional[int] =convert_config(model[0] , SCREAMING_SNAKE_CASE ) a__ : int =model[0].eval() a__ : List[str] =True if config.feat_extract_norm == "layer" else False a__ : Optional[int] =WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , ) if is_finetuned: if dict_path: a__ : List[Any] =Dictionary.load(SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq a__ : Any =target_dict.pad_index a__ : Any =target_dict.bos_index a__ : List[Any] =target_dict.pad_index a__ : Dict =target_dict.bos_index a__ : Optional[int] =target_dict.eos_index a__ : Dict =len(target_dict.symbols ) a__ : List[str] =os.path.join(SCREAMING_SNAKE_CASE , "vocab.json" ) if not os.path.isdir(SCREAMING_SNAKE_CASE ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(SCREAMING_SNAKE_CASE ) ) return os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as vocab_handle: json.dump(target_dict.indices , SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =WavaVecaCTCTokenizer( SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="|" , do_lower_case=SCREAMING_SNAKE_CASE , ) a__ : List[Any] =WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =SEWForCTC(SCREAMING_SNAKE_CASE ) else: a__ : int =SEWModel(SCREAMING_SNAKE_CASE ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE ) recursively_load_weights(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCAmelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCAmelCase : Tuple = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
95
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class __lowerCAmelCase : def _lowercase ( self , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError() def _lowercase ( self ) -> int: '''simple docstring''' raise NotImplementedError() class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , **lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : str =tokenizer a__ : List[str] =skip_prompt a__ : List[Any] =decode_kwargs # variables used in the streaming process a__ : Dict =[] a__ : int =0 a__ : str =True def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError("TextStreamer only supports batch size 1" ) elif len(value.shape ) > 1: a__ : Any =value[0] if self.skip_prompt and self.next_tokens_are_prompt: a__ : Dict =False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith("\n" ): a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 # If the last token is a CJK character, we print the characters. elif len(lowerCAmelCase__ ) > 0 and self._is_chinese_char(ord(text[-1] ) ): a__ : List[str] =text[self.print_len :] self.print_len += len(lowerCAmelCase__ ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: a__ : str =text[self.print_len : text.rfind(" " ) + 1] self.print_len += len(lowerCAmelCase__ ) self.on_finalized_text(lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' if len(self.token_cache ) > 0: a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 else: a__ : Union[str, Any] ="" a__ : Any =True self.on_finalized_text(lowerCAmelCase__ , stream_end=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> Optional[Any]: '''simple docstring''' print(lowerCAmelCase__ , flush=lowerCAmelCase__ , end="" if not stream_end else None ) def _lowercase ( self , lowerCAmelCase__ ) -> str: '''simple docstring''' if ( (cp >= 0X4E_00 and cp <= 0X9F_FF) or (cp >= 0X34_00 and cp <= 0X4D_BF) # or (cp >= 0X2_00_00 and cp <= 0X2_A6_DF) # or (cp >= 0X2_A7_00 and cp <= 0X2_B7_3F) # or (cp >= 0X2_B7_40 and cp <= 0X2_B8_1F) # or (cp >= 0X2_B8_20 and cp <= 0X2_CE_AF) # or (cp >= 0XF9_00 and cp <= 0XFA_FF) or (cp >= 0X2_F8_00 and cp <= 0X2_FA_1F) # ): # return True return False class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , lowerCAmelCase__ = None , **lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' super().__init__(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : str =Queue() a__ : Optional[Any] =None a__ : Any =timeout def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> List[str]: '''simple docstring''' self.text_queue.put(lowerCAmelCase__ , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self ) -> Dict: '''simple docstring''' return self def _lowercase ( self ) -> int: '''simple docstring''' a__ : int =self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
95
1
from collections import deque def _A ( SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" a__ : str =len(SCREAMING_SNAKE_CASE ) a__ : Tuple =deque() a__ : List[Any] =[False for _ in range(SCREAMING_SNAKE_CASE )] a__ : int =[-1 for _ in range(SCREAMING_SNAKE_CASE )] a__ : List[Any] =index_of[:] def strong_connect(SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Tuple ): a__ : Optional[int] =index # the number when this node is seen a__ : Any =index # lowest rank node reachable from here index += 1 stack.append(SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =True for w in g[v]: if index_of[w] == -1: a__ : Union[str, Any] =strong_connect(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : int =( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: a__ : Optional[int] =( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: a__ : Optional[int] =[] a__ : str =stack.pop() a__ : Any =False component.append(SCREAMING_SNAKE_CASE ) while w != v: a__ : str =stack.pop() a__ : Tuple =False component.append(SCREAMING_SNAKE_CASE ) components.append(SCREAMING_SNAKE_CASE ) return index a__ : Optional[Any] =[] for v in range(SCREAMING_SNAKE_CASE ): if index_of[v] == -1: strong_connect(SCREAMING_SNAKE_CASE , 0 , SCREAMING_SNAKE_CASE ) return components def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Any =[[] for _ in range(SCREAMING_SNAKE_CASE )] for u, v in edges: g[u].append(SCREAMING_SNAKE_CASE ) return g if __name__ == "__main__": # Test UpperCAmelCase : int = 7 UpperCAmelCase : Union[str, Any] = [0, 0, 1, 2, 3, 3, 4, 4, 6] UpperCAmelCase : Optional[Any] = [1, 3, 2, 0, 1, 4, 5, 6, 5] UpperCAmelCase : Tuple = [(u, v) for u, v in zip(source, target)] UpperCAmelCase : Any = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
95
def _A ( SCREAMING_SNAKE_CASE : int = 50 ): """simple docstring""" a__ : Any =[1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
95
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_big_bird import BigBirdTokenizer else: UpperCAmelCase : int = None UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : List[Any] = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase : Union[str, Any] = { """vocab_file""": { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model""", """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model""" ), }, """tokenizer_file""": { """google/bigbird-roberta-base""": ( """https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json""" ), """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json""" ), }, } UpperCAmelCase : Dict = { """google/bigbird-roberta-base""": 4096, """google/bigbird-roberta-large""": 4096, """google/bigbird-base-trivia-itc""": 4096, } UpperCAmelCase : Union[str, Any] = """▁""" class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Union[str, Any] = VOCAB_FILES_NAMES _lowercase : Any = PRETRAINED_VOCAB_FILES_MAP _lowercase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Tuple = BigBirdTokenizer _lowercase : Any = ["""input_ids""", """attention_mask"""] _lowercase : List[int] = [] def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="[SEP]" , lowerCAmelCase__="[MASK]" , lowerCAmelCase__="[CLS]" , **lowerCAmelCase__ , ) -> int: '''simple docstring''' a__ : List[Any] =AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else bos_token a__ : Optional[Any] =AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else eos_token a__ : Any =AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else unk_token a__ : int =AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else pad_token a__ : List[Any] =AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else cls_token a__ : Optional[Any] =AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it a__ : Optional[Any] =AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else mask_token super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : Tuple =vocab_file a__ : str =False if not self.vocab_file else True def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: '''simple docstring''' a__ : str =[self.sep_token_id] a__ : Union[str, Any] =[self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(lowerCAmelCase__ )) + [1] return [1] + ([0] * len(lowerCAmelCase__ )) + [1] + ([0] * len(lowerCAmelCase__ )) + [1] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: '''simple docstring''' a__ : Union[str, Any] =[self.sep_token_id] a__ : List[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: '''simple docstring''' 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(lowerCAmelCase__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return a__ : Optional[int] =os.path.join( lowerCAmelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase__ ): copyfile(self.vocab_file , lowerCAmelCase__ ) return (out_vocab_file,)
95
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if len(SCREAMING_SNAKE_CASE ) == 0: return [] a__ , a__ : int =min(SCREAMING_SNAKE_CASE ), max(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =int(max_value - min_value ) + 1 a__ : list[list] =[[] for _ in range(SCREAMING_SNAKE_CASE )] for i in my_list: buckets[int(i - min_value )].append(SCREAMING_SNAKE_CASE ) return [v for bucket in buckets for v in sorted(SCREAMING_SNAKE_CASE )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
95
1
import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging UpperCAmelCase : int = { """cola""": 2, """mnli""": 3, """mrpc""": 2, """sst-2""": 2, """sts-b""": 1, """qqp""": 2, """qnli""": 2, """rte""": 2, """wnli""": 2, } logging.set_verbosity_info() def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any]=None ): """simple docstring""" a__ : Optional[int] =XLNetConfig.from_json_file(SCREAMING_SNAKE_CASE ) a__ : Dict =finetuning_task.lower() if finetuning_task is not None else "" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(f'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}''' ) a__ : List[str] =finetuning_task a__ : Tuple =GLUE_TASKS_NUM_LABELS[finetuning_task] a__ : List[Any] =XLNetForSequenceClassification(SCREAMING_SNAKE_CASE ) elif "squad" in finetuning_task: a__ : Optional[int] =finetuning_task a__ : Dict =XLNetForQuestionAnswering(SCREAMING_SNAKE_CASE ) else: a__ : List[Any] =XLNetLMHeadModel(SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Save pytorch-model a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print(f'''Save PyTorch model to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE ) print(f'''Save configuration file to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--xlnet_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained XLNet model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the folder to store the PyTorch model or dataset/vocab.""", ) parser.add_argument( """--finetuning_task""", default=None, type=str, help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""", ) UpperCAmelCase : int = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
95
import numpy as np def _A ( SCREAMING_SNAKE_CASE : np.array ): """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
95
1
import math def _A ( SCREAMING_SNAKE_CASE : list , SCREAMING_SNAKE_CASE : int = 0 , SCREAMING_SNAKE_CASE : int = 0 ): """simple docstring""" a__ : Union[str, Any] =end or len(SCREAMING_SNAKE_CASE ) for i in range(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): a__ : Dict =i a__ : Optional[int] =array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: a__ : Tuple =array[temp_index - 1] temp_index -= 1 a__ : Any =temp_index_value return array def _A ( SCREAMING_SNAKE_CASE : list , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): # Max Heap """simple docstring""" a__ : Optional[int] =index a__ : Any =2 * index + 1 # Left Node a__ : Tuple =2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: a__ : int =left_index if right_index < heap_size and array[largest] < array[right_index]: a__ : int =right_index if largest != index: a__ , a__ : str =array[largest], array[index] heapify(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" a__ : Any =len(SCREAMING_SNAKE_CASE ) for i in range(n // 2 , -1 , -1 ): heapify(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for i in range(n - 1 , 0 , -1 ): a__ , a__ : Optional[Any] =array[0], array[i] heapify(SCREAMING_SNAKE_CASE , 0 , SCREAMING_SNAKE_CASE ) return array def _A ( SCREAMING_SNAKE_CASE : list , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def _A ( SCREAMING_SNAKE_CASE : list , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : str =low a__ : List[Any] =high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i a__ , a__ : Tuple =array[j], array[i] i += 1 def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if len(SCREAMING_SNAKE_CASE ) == 0: return array a__ : str =2 * math.ceil(math.loga(len(SCREAMING_SNAKE_CASE ) ) ) a__ : str =16 return intro_sort(SCREAMING_SNAKE_CASE , 0 , len(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : list , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" while end - start > size_threshold: if max_depth == 0: return heap_sort(SCREAMING_SNAKE_CASE ) max_depth -= 1 a__ : Dict =median_of_a(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , start + ((end - start) // 2) + 1 , end - 1 ) a__ : Any =partition(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) intro_sort(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Tuple =p return insertion_sort(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase : Optional[Any] = input("""Enter numbers separated by a comma : """).strip() UpperCAmelCase : Dict = [float(item) for item in user_input.split(""",""")] print(sort(unsorted))
95
import numpy # List of input, output pairs UpperCAmelCase : str = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) UpperCAmelCase : Optional[int] = (((515, 22, 13), 555), ((61, 35, 49), 150)) UpperCAmelCase : str = [2, 4, 1, 5] UpperCAmelCase : List[str] = len(train_data) UpperCAmelCase : Dict = 0.0_0_9 def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Tuple="train" ): """simple docstring""" return calculate_hypothesis_value(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) - output( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : Tuple =0 for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : int=m ): """simple docstring""" a__ : Any =0 for i in range(SCREAMING_SNAKE_CASE ): if index == -1: summation_value += _error(SCREAMING_SNAKE_CASE ) else: summation_value += _error(SCREAMING_SNAKE_CASE ) * train_data[i][0][index] return summation_value def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Any =summation_of_cost_derivative(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) / m return cost_derivative_value def _A ( ): """simple docstring""" global parameter_vector # Tune these values to set a tolerance value for predicted output a__ : Dict =0.0_0_0_0_0_2 a__ : Union[str, Any] =0 a__ : Any =0 while True: j += 1 a__ : Any =[0, 0, 0, 0] for i in range(0 , len(SCREAMING_SNAKE_CASE ) ): a__ : Tuple =get_cost_derivative(i - 1 ) a__ : List[Any] =( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE , rtol=SCREAMING_SNAKE_CASE , ): break a__ : Optional[Any] =temp_parameter_vector print(("Number of iterations:", j) ) def _A ( ): """simple docstring""" for i in range(len(SCREAMING_SNAKE_CASE ) ): print(("Actual output value:", output(SCREAMING_SNAKE_CASE , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(SCREAMING_SNAKE_CASE , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("""\nTesting gradient descent for a linear hypothesis function.\n""") test_gradient_descent()
95
1
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Tuple = [ ["""attention""", """attn"""], ["""encoder_attention""", """encoder_attn"""], ["""q_lin""", """q_proj"""], ["""k_lin""", """k_proj"""], ["""v_lin""", """v_proj"""], ["""out_lin""", """out_proj"""], ["""norm_embeddings""", """layernorm_embedding"""], ["""position_embeddings""", """embed_positions"""], ["""embeddings""", """embed_tokens"""], ["""ffn.lin""", """fc"""], ] def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: a__ : Union[str, Any] =k.replace(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if k.startswith("encoder" ): a__ : Tuple =k.replace(".attn" , ".self_attn" ) a__ : List[str] =k.replace("norm1" , "self_attn_layer_norm" ) a__ : int =k.replace("norm2" , "final_layer_norm" ) elif k.startswith("decoder" ): a__ : Tuple =k.replace("norm1" , "self_attn_layer_norm" ) a__ : Any =k.replace("norm2" , "encoder_attn_layer_norm" ) a__ : Optional[Any] =k.replace("norm3" , "final_layer_norm" ) return k def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : str =[ "model.encoder.layernorm_embedding.weight", "model.encoder.layernorm_embedding.bias", "model.decoder.layernorm_embedding.weight", "model.decoder.layernorm_embedding.bias", ] for k in keys: a__ : List[Any] =sd.pop(SCREAMING_SNAKE_CASE ) a__ : List[Any] =k.replace("layernorm_embedding" , "layer_norm" ) assert new_k not in sd a__ : Union[str, Any] =v UpperCAmelCase : Any = ["""START"""] @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" a__ : int =torch.load(SCREAMING_SNAKE_CASE , map_location="cpu" ) a__ : Any =model["model"] a__ : List[Any] =BlenderbotConfig.from_json_file(SCREAMING_SNAKE_CASE ) a__ : Optional[Any] =BlenderbotForConditionalGeneration(SCREAMING_SNAKE_CASE ) a__ : List[Any] =m.model.state_dict().keys() a__ : List[Any] =[] a__ : List[Any] ={} for k, v in sd.items(): if k in IGNORE_KEYS: continue a__ : List[str] =rename_state_dict_key(SCREAMING_SNAKE_CASE ) if new_k not in valid_keys: failures.append([k, new_k] ) else: a__ : List[str] =v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(SCREAMING_SNAKE_CASE ) m.model.load_state_dict(SCREAMING_SNAKE_CASE , strict=SCREAMING_SNAKE_CASE ) m.half() m.save_pretrained(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("""--src_path""", type=str, help="""like blenderbot-model.bin""") parser.add_argument("""--save_dir""", default="""hf_blenderbot""", type=str, help="""Where to save converted model.""") parser.add_argument( """--hf_config_json""", default="""blenderbot-3b-config.json""", type=str, help="""Path to config to use""" ) UpperCAmelCase : List[str] = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
95
def _A ( SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" a__ : Optional[Any] =len(SCREAMING_SNAKE_CASE ) while cur > 1: # Find the maximum number in arr a__ : List[Any] =arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi a__ : int =arr[mi::-1] + arr[mi + 1 : len(SCREAMING_SNAKE_CASE )] # Reverse whole list a__ : List[str] =arr[cur - 1 :: -1] + arr[cur : len(SCREAMING_SNAKE_CASE )] cur -= 1 return arr if __name__ == "__main__": UpperCAmelCase : int = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase : Optional[int] = [int(item) for item in user_input.split(""",""")] print(pancake_sort(unsorted))
95
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : Tuple = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] UpperCAmelCase : int = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] UpperCAmelCase : List[Any] = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): UpperCAmelCase : str = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
95
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Any =tempfile.mkdtemp() # fmt: off a__ : List[Any] =["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on a__ : str =dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) a__ : List[Any] =["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""] a__ : Optional[int] ={"unk_token": "<unk>"} a__ : Optional[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) a__ : Tuple =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowerCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(lowerCAmelCase__ ) ) a__ : Optional[Any] ={ "do_resize": True, "size": 2_0, "do_center_crop": True, "crop_size": 1_8, "do_normalize": True, "image_mean": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], "image_std": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } a__ : Dict =os.path.join(self.tmpdirname , lowerCAmelCase__ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Any: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =[np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] a__ : List[Any] =[Image.fromarray(np.moveaxis(lowerCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Union[str, Any] =self.get_tokenizer() a__ : int =self.get_rust_tokenizer() a__ : List[str] =self.get_image_processor() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) a__ : Optional[Any] =CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=lowerCAmelCase__ ) a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) a__ : Dict =CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor , lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a__ : str =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) a__ : int =self.get_image_processor(do_normalize=lowerCAmelCase__ , padding_value=1.0 ) a__ : Optional[Any] =CLIPSegProcessor.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 _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : str =self.get_image_processor() a__ : Optional[int] =self.get_tokenizer() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : str =self.prepare_image_inputs() a__ : Any =image_processor(lowerCAmelCase__ , return_tensors="np" ) a__ : Optional[int] =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 _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : List[Any] =self.get_tokenizer() a__ : Optional[int] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Union[str, Any] ="lower newer" a__ : List[str] =processor(text=lowerCAmelCase__ ) a__ : str =tokenizer(lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =self.get_image_processor() a__ : Dict =self.get_tokenizer() a__ : Union[str, Any] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict ="lower newer" a__ : int =self.prepare_image_inputs() a__ : Any =processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> str: '''simple docstring''' a__ : Union[str, Any] =self.get_image_processor() a__ : Optional[Any] =self.get_tokenizer() a__ : str =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : int =self.prepare_image_inputs() a__ : Union[str, Any] =self.prepare_image_inputs() a__ : Tuple =processor(images=lowerCAmelCase__ , visual_prompt=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "conditional_pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : Any =self.get_tokenizer() a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a__ : Optional[Any] =processor.batch_decode(lowerCAmelCase__ ) a__ : Dict =tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
95
1
def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" a__ : Optional[Any] =[0] * len(SCREAMING_SNAKE_CASE ) for i in range(1 , len(SCREAMING_SNAKE_CASE ) ): # use last results for better performance - dynamic programming a__ : Tuple =prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: a__ : str =prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 a__ : str =j return prefix_result def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" return max(prefix_function(SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod()
95
def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) if len(SCREAMING_SNAKE_CASE ) == 1: return True a__ : Union[str, Any] =series[1] - series[0] for index in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) a__ : Any =0 for val in series: answer += val return answer / len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
95
1
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class __lowerCAmelCase : def _lowercase ( self , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError() def _lowercase ( self ) -> int: '''simple docstring''' raise NotImplementedError() class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , **lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : str =tokenizer a__ : List[str] =skip_prompt a__ : List[Any] =decode_kwargs # variables used in the streaming process a__ : Dict =[] a__ : int =0 a__ : str =True def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError("TextStreamer only supports batch size 1" ) elif len(value.shape ) > 1: a__ : Any =value[0] if self.skip_prompt and self.next_tokens_are_prompt: a__ : Dict =False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith("\n" ): a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 # If the last token is a CJK character, we print the characters. elif len(lowerCAmelCase__ ) > 0 and self._is_chinese_char(ord(text[-1] ) ): a__ : List[str] =text[self.print_len :] self.print_len += len(lowerCAmelCase__ ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: a__ : str =text[self.print_len : text.rfind(" " ) + 1] self.print_len += len(lowerCAmelCase__ ) self.on_finalized_text(lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' if len(self.token_cache ) > 0: a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 else: a__ : Union[str, Any] ="" a__ : Any =True self.on_finalized_text(lowerCAmelCase__ , stream_end=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> Optional[Any]: '''simple docstring''' print(lowerCAmelCase__ , flush=lowerCAmelCase__ , end="" if not stream_end else None ) def _lowercase ( self , lowerCAmelCase__ ) -> str: '''simple docstring''' if ( (cp >= 0X4E_00 and cp <= 0X9F_FF) or (cp >= 0X34_00 and cp <= 0X4D_BF) # or (cp >= 0X2_00_00 and cp <= 0X2_A6_DF) # or (cp >= 0X2_A7_00 and cp <= 0X2_B7_3F) # or (cp >= 0X2_B7_40 and cp <= 0X2_B8_1F) # or (cp >= 0X2_B8_20 and cp <= 0X2_CE_AF) # or (cp >= 0XF9_00 and cp <= 0XFA_FF) or (cp >= 0X2_F8_00 and cp <= 0X2_FA_1F) # ): # return True return False class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , lowerCAmelCase__ = None , **lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' super().__init__(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : str =Queue() a__ : Optional[Any] =None a__ : Any =timeout def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> List[str]: '''simple docstring''' self.text_queue.put(lowerCAmelCase__ , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self ) -> Dict: '''simple docstring''' return self def _lowercase ( self ) -> int: '''simple docstring''' a__ : int =self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
95
import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Tuple = """M-CLIP""" def __init__( self , lowerCAmelCase__=1_0_2_4 , lowerCAmelCase__=7_6_8 , **lowerCAmelCase__ ) -> Any: '''simple docstring''' a__ : int =transformerDimSize a__ : Dict =imageDimSize super().__init__(**lowerCAmelCase__ ) class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = MCLIPConfig def __init__( self , lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> List[str]: '''simple docstring''' super().__init__(lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Tuple =XLMRobertaModel(lowerCAmelCase__ ) a__ : List[str] =torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[Any] =self.transformer(input_ids=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ )[0] a__ : int =(embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(lowerCAmelCase__ ), embs
95
1
def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" def merge(SCREAMING_SNAKE_CASE : list , SCREAMING_SNAKE_CASE : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(SCREAMING_SNAKE_CASE ) <= 1: return collection a__ : Optional[Any] =len(SCREAMING_SNAKE_CASE ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase : Tuple = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase : List[Any] = [int(item) for item in user_input.split(""",""")] print(*merge_sort(unsorted), sep=""",""")
95
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 ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to properly calculate the metrics on the # validation dataset when in a distributed system, and builds off the # `nlp_example.py` script. # # 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 help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # 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 : Any = 16 UpperCAmelCase : str = 32 def _A ( SCREAMING_SNAKE_CASE : Accelerator , SCREAMING_SNAKE_CASE : int = 16 ): """simple docstring""" a__ : int =AutoTokenizer.from_pretrained("bert-base-cased" ) a__ : List[str] =load_dataset("glue" , "mrpc" ) def tokenize_function(SCREAMING_SNAKE_CASE : List[Any] ): # max_length=None => use the model max length (it's actually the default) a__ : int =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__ : Dict =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__ : Dict =tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(SCREAMING_SNAKE_CASE : str ): # On TPU it's best to pad everything to the same length or training will be very slow. a__ : Optional[Any] =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__ : str =16 elif accelerator.mixed_precision != "no": a__ : Union[str, Any] =8 else: a__ : List[str] =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__ : Any =DataLoader( tokenized_datasets["train"] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE ) a__ : int =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 : str = mocked_dataloaders # noqa: F811 def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : str ): """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , SCREAMING_SNAKE_CASE ) == "1": a__ : Tuple =2 # Initialize accelerator a__ : int =Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a__ : Optional[int] =config["lr"] a__ : Union[str, Any] =int(config["num_epochs"] ) a__ : Any =int(config["seed"] ) a__ : Dict =int(config["batch_size"] ) a__ : int =evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation a__ : int =1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: a__ : Dict =batch_size // MAX_GPU_BATCH_SIZE a__ : Tuple =MAX_GPU_BATCH_SIZE set_seed(SCREAMING_SNAKE_CASE ) a__ , a__ : Optional[int] =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__ : List[str] =model.to(accelerator.device ) # Instantiate optimizer a__ : List[Any] =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) // gradient_accumulation_steps , ) # 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__ : Optional[int] =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() 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 ) a__ : Dict =model(**SCREAMING_SNAKE_CASE ) a__ : List[Any] =outputs.loss a__ : List[str] =loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() a__ : Optional[Any] =0 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__ : Any =model(**SCREAMING_SNAKE_CASE ) a__ : str =outputs.logits.argmax(dim=-1 ) a__ , a__ : List[str] =accelerator.gather((predictions, batch["labels"]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(SCREAMING_SNAKE_CASE ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples a__ : Optional[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] a__ : Dict =references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=SCREAMING_SNAKE_CASE , references=SCREAMING_SNAKE_CASE , ) a__ : Tuple =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , SCREAMING_SNAKE_CASE ) def _A ( ): """simple docstring""" a__ : List[str] =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." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) a__ : str =parser.parse_args() a__ : Optional[int] ={"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
95
1
import numpy # List of input, output pairs UpperCAmelCase : str = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) UpperCAmelCase : Optional[int] = (((515, 22, 13), 555), ((61, 35, 49), 150)) UpperCAmelCase : str = [2, 4, 1, 5] UpperCAmelCase : List[str] = len(train_data) UpperCAmelCase : Dict = 0.0_0_9 def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Tuple="train" ): """simple docstring""" return calculate_hypothesis_value(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) - output( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : Tuple =0 for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : int=m ): """simple docstring""" a__ : Any =0 for i in range(SCREAMING_SNAKE_CASE ): if index == -1: summation_value += _error(SCREAMING_SNAKE_CASE ) else: summation_value += _error(SCREAMING_SNAKE_CASE ) * train_data[i][0][index] return summation_value def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Any =summation_of_cost_derivative(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) / m return cost_derivative_value def _A ( ): """simple docstring""" global parameter_vector # Tune these values to set a tolerance value for predicted output a__ : Dict =0.0_0_0_0_0_2 a__ : Union[str, Any] =0 a__ : Any =0 while True: j += 1 a__ : Any =[0, 0, 0, 0] for i in range(0 , len(SCREAMING_SNAKE_CASE ) ): a__ : Tuple =get_cost_derivative(i - 1 ) a__ : List[Any] =( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE , rtol=SCREAMING_SNAKE_CASE , ): break a__ : Optional[Any] =temp_parameter_vector print(("Number of iterations:", j) ) def _A ( ): """simple docstring""" for i in range(len(SCREAMING_SNAKE_CASE ) ): print(("Actual output value:", output(SCREAMING_SNAKE_CASE , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(SCREAMING_SNAKE_CASE , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("""\nTesting gradient descent for a linear hypothesis function.\n""") test_gradient_descent()
95
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 MobileViTImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] =size if size is not None else {"shortest_edge": 2_0} a__ : List[str] =crop_size if crop_size is not None else {"height": 1_8, "width": 1_8} a__ : Tuple =parent a__ : Union[str, Any] =batch_size a__ : List[str] =num_channels a__ : List[Any] =image_size a__ : str =min_resolution a__ : Optional[int] =max_resolution a__ : Tuple =do_resize a__ : Union[str, Any] =size a__ : List[Any] =do_center_crop a__ : List[str] =crop_size a__ : Optional[int] =do_flip_channel_order def _lowercase ( self ) -> Optional[int]: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : int = MobileViTImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : Tuple =MobileViTImageProcessingTester(self ) @property def _lowercase ( self ) -> List[str]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : str =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_flip_channel_order" ) ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : List[Any] =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 2_0} ) self.assertEqual(image_processor.crop_size , {"height": 1_8, "width": 1_8} ) a__ : Union[str, Any] =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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' pass def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : 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 a__ : List[Any] =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : List[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input a__ : 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 a__ : int =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : int =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input a__ : List[str] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a__ : List[str] =image_processing(lowerCAmelCase__ , 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"], ) , )
95
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { """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 __lowerCAmelCase ( UpperCamelCase__): _lowercase : Union[str, Any] = """visual_bert""" def __init__( self , lowerCAmelCase__=3_0_5_2_2 , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__=1 , lowerCAmelCase__=0 , lowerCAmelCase__=2 , **lowerCAmelCase__ , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Any =vocab_size a__ : Optional[Any] =max_position_embeddings a__ : str =hidden_size a__ : str =visual_embedding_dim a__ : Optional[int] =num_hidden_layers a__ : Dict =num_attention_heads a__ : Tuple =intermediate_size a__ : List[str] =hidden_act a__ : int =hidden_dropout_prob a__ : Dict =attention_probs_dropout_prob a__ : int =initializer_range a__ : Dict =type_vocab_size a__ : List[Any] =layer_norm_eps a__ : Optional[int] =bypass_transformer a__ : Any =special_visual_initialize
95
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 MobileNetVaImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=None , ) -> Optional[int]: '''simple docstring''' a__ : str =size if size is not None else {"shortest_edge": 2_0} a__ : Union[str, Any] =crop_size if crop_size is not None else {"height": 1_8, "width": 1_8} a__ : Tuple =parent a__ : Optional[int] =batch_size a__ : Any =num_channels a__ : List[str] =image_size a__ : Dict =min_resolution a__ : List[Any] =max_resolution a__ : Dict =do_resize a__ : Union[str, Any] =size a__ : str =do_center_crop a__ : List[str] =crop_size def _lowercase ( self ) -> str: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : Optional[Any] = MobileNetVaImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =MobileNetVaImageProcessingTester(self ) @property def _lowercase ( self ) -> List[str]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "crop_size" ) ) def _lowercase ( self ) -> str: '''simple docstring''' a__ : Any =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 2_0} ) self.assertEqual(image_processor.crop_size , {"height": 1_8, "width": 1_8} ) a__ : Dict =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 _lowercase ( self ) -> Any: '''simple docstring''' pass def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Dict =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : Optional[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : List[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 a__ : Dict =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> int: '''simple docstring''' a__ : str =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input a__ : List[str] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a__ : Union[str, Any] =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : int =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input a__ : Optional[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 a__ : str =image_processing(lowerCAmelCase__ , 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"], ) , )
95
1
import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor UpperCAmelCase : int = logging.get_logger(__name__) class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> None: '''simple docstring''' warnings.warn( "The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use VideoMAEImageProcessor instead." , lowerCAmelCase__ , ) super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__ )
95
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Any = { """configuration_convbert""": ["""CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvBertConfig""", """ConvBertOnnxConfig"""], """tokenization_convbert""": ["""ConvBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] = ["""ConvBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[str] = [ """CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConvBertForMaskedLM""", """ConvBertForMultipleChoice""", """ConvBertForQuestionAnswering""", """ConvBertForSequenceClassification""", """ConvBertForTokenClassification""", """ConvBertLayer""", """ConvBertModel""", """ConvBertPreTrainedModel""", """load_tf_weights_in_convbert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ """TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFConvBertForMaskedLM""", """TFConvBertForMultipleChoice""", """TFConvBertForQuestionAnswering""", """TFConvBertForSequenceClassification""", """TFConvBertForTokenClassification""", """TFConvBertLayer""", """TFConvBertModel""", """TFConvBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
95
1
def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : int =(num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def _A ( ): """simple docstring""" print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
95
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : Tuple = { """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Any = """swin2sr""" _lowercase : Tuple = { """hidden_size""": """embed_dim""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , lowerCAmelCase__=6_4 , lowerCAmelCase__=1 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8_0 , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=8 , lowerCAmelCase__=2.0 , lowerCAmelCase__=True , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__="gelu" , lowerCAmelCase__=False , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-5 , lowerCAmelCase__=2 , lowerCAmelCase__=1.0 , lowerCAmelCase__="1conv" , lowerCAmelCase__="pixelshuffle" , **lowerCAmelCase__ , ) -> int: '''simple docstring''' super().__init__(**lowerCAmelCase__ ) a__ : Optional[Any] =image_size a__ : Dict =patch_size a__ : Tuple =num_channels a__ : Union[str, Any] =embed_dim a__ : Optional[Any] =depths a__ : List[str] =len(lowerCAmelCase__ ) a__ : Any =num_heads a__ : Any =window_size a__ : str =mlp_ratio a__ : List[str] =qkv_bias a__ : Dict =hidden_dropout_prob a__ : List[str] =attention_probs_dropout_prob a__ : Dict =drop_path_rate a__ : Optional[Any] =hidden_act a__ : Union[str, Any] =use_absolute_embeddings a__ : Optional[Any] =layer_norm_eps a__ : List[Any] =initializer_range a__ : int =upscale a__ : Optional[int] =img_range a__ : Any =resi_connection a__ : Optional[Any] =upsampler
95
1
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def _A ( SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Any =cva.getAffineTransform(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return cva.warpAffine(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , (rows, cols) ) if __name__ == "__main__": # read original image UpperCAmelCase : Optional[Any] = cva.imread( str(Path(__file__).resolve().parent.parent / """image_data""" / """lena.jpg""") ) # turn image in gray scale value UpperCAmelCase : Tuple = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape UpperCAmelCase , UpperCAmelCase : Optional[int] = gray_img.shape # set different points to rotate image UpperCAmelCase : Optional[Any] = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) UpperCAmelCase : Optional[Any] = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) UpperCAmelCase : Dict = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) UpperCAmelCase : Any = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list UpperCAmelCase : Optional[Any] = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations UpperCAmelCase : int = plt.figure(1) UpperCAmelCase : Any = ["""Original""", """Rotation 1""", """Rotation 2""", """Rotation 3"""] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, """gray""") plt.title(titles[i]) plt.axis("""off""") plt.subplots_adjust(left=0.0, bottom=0.0_5, right=1.0, top=0.9_5) plt.show()
95
from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class __lowerCAmelCase : pass
95
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Any =tempfile.mkdtemp() # fmt: off a__ : List[Any] =["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on a__ : str =dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) a__ : List[Any] =["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""] a__ : Optional[int] ={"unk_token": "<unk>"} a__ : Optional[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) a__ : Tuple =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowerCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(lowerCAmelCase__ ) ) a__ : Optional[Any] ={ "do_resize": True, "size": 2_0, "do_center_crop": True, "crop_size": 1_8, "do_normalize": True, "image_mean": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], "image_std": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } a__ : Dict =os.path.join(self.tmpdirname , lowerCAmelCase__ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Any: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =[np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] a__ : List[Any] =[Image.fromarray(np.moveaxis(lowerCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Union[str, Any] =self.get_tokenizer() a__ : int =self.get_rust_tokenizer() a__ : List[str] =self.get_image_processor() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) a__ : Optional[Any] =CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=lowerCAmelCase__ ) a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) a__ : Dict =CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor , lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a__ : str =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) a__ : int =self.get_image_processor(do_normalize=lowerCAmelCase__ , padding_value=1.0 ) a__ : Optional[Any] =CLIPSegProcessor.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 _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : str =self.get_image_processor() a__ : Optional[int] =self.get_tokenizer() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : str =self.prepare_image_inputs() a__ : Any =image_processor(lowerCAmelCase__ , return_tensors="np" ) a__ : Optional[int] =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 _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : List[Any] =self.get_tokenizer() a__ : Optional[int] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Union[str, Any] ="lower newer" a__ : List[str] =processor(text=lowerCAmelCase__ ) a__ : str =tokenizer(lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =self.get_image_processor() a__ : Dict =self.get_tokenizer() a__ : Union[str, Any] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict ="lower newer" a__ : int =self.prepare_image_inputs() a__ : Any =processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> str: '''simple docstring''' a__ : Union[str, Any] =self.get_image_processor() a__ : Optional[Any] =self.get_tokenizer() a__ : str =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : int =self.prepare_image_inputs() a__ : Union[str, Any] =self.prepare_image_inputs() a__ : Tuple =processor(images=lowerCAmelCase__ , visual_prompt=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "conditional_pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : Any =self.get_tokenizer() a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a__ : Optional[Any] =processor.batch_decode(lowerCAmelCase__ ) a__ : Dict =tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
95
# 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 __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = """philschmid/bart-large-cnn-samsum""" _lowercase : List[Any] = ( """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.""" ) _lowercase : Any = """summarizer""" _lowercase : Any = AutoTokenizer _lowercase : str = AutoModelForSeqaSeqLM _lowercase : Optional[int] = ["""text"""] _lowercase : Optional[int] = ["""text"""] def _lowercase ( self , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' return self.pre_processor(lowerCAmelCase__ , return_tensors="pt" , truncation=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return self.model.generate(**lowerCAmelCase__ )[0] def _lowercase ( self , lowerCAmelCase__ ) -> Any: '''simple docstring''' return self.pre_processor.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ )
95
1
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCAmelCase : Tuple = logging.get_logger(__name__) class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> None: '''simple docstring''' warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , lowerCAmelCase__ , ) super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__ )
95
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer UpperCAmelCase : int = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase : List[Any] = [ """small""", """small-base""", """medium""", """medium-base""", """intermediate""", """intermediate-base""", """large""", """large-base""", """xlarge""", """xlarge-base""", ] UpperCAmelCase : Optional[int] = { """vocab_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt""", """funnel-transformer/small-base""": """https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt""", """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt""", """funnel-transformer/large-base""": """https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt""", """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json""", """funnel-transformer/small-base""": ( """https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json""" ), """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json""", """funnel-transformer/large-base""": ( """https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json""" ), """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json""" ), }, } UpperCAmelCase : Optional[int] = {F"""funnel-transformer/{name}""": 512 for name in _model_names} UpperCAmelCase : Optional[int] = {F"""funnel-transformer/{name}""": {"""do_lower_case""": True} for name in _model_names} class __lowerCAmelCase ( UpperCamelCase__): _lowercase : str = VOCAB_FILES_NAMES _lowercase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowercase : Dict = PRETRAINED_INIT_CONFIGURATION _lowercase : Union[str, Any] = FunnelTokenizer _lowercase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : int = 2 def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<sep>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="<cls>" , lowerCAmelCase__="<mask>" , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__="##" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , clean_text=lowerCAmelCase__ , tokenize_chinese_chars=lowerCAmelCase__ , strip_accents=lowerCAmelCase__ , wordpieces_prefix=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : Optional[Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowerCAmelCase__ ) != do_lower_case or normalizer_state.get("strip_accents" , lowerCAmelCase__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowerCAmelCase__ ) != tokenize_chinese_chars ): a__ : List[str] =getattr(lowerCAmelCase__ , normalizer_state.pop("type" ) ) a__ : Union[str, Any] =do_lower_case a__ : Any =strip_accents a__ : Optional[Any] =tokenize_chinese_chars a__ : Dict =normalizer_class(**lowerCAmelCase__ ) a__ : Any =do_lower_case def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> str: '''simple docstring''' a__ : Dict =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] =[self.sep_token_id] a__ : Union[str, Any] =[self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: '''simple docstring''' a__ : Tuple =self._tokenizer.model.save(lowerCAmelCase__ , name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ )
95
1
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin UpperCAmelCase : Dict = random.Random() if is_torch_available(): import torch def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any=1.0 , SCREAMING_SNAKE_CASE : Union[str, Any]=None , SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" if rng is None: a__ : Any =global_rng a__ : List[Any] =[] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=2_0_0_0 , lowerCAmelCase__=1 , lowerCAmelCase__=0.0 , lowerCAmelCase__=1_6_0_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=True , ) -> Any: '''simple docstring''' a__ : List[Any] =parent a__ : Optional[int] =batch_size a__ : Optional[Any] =min_seq_length a__ : List[str] =max_seq_length a__ : Any =(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) a__ : Dict =feature_size a__ : Dict =padding_value a__ : Optional[int] =sampling_rate a__ : Optional[int] =return_attention_mask a__ : Optional[Any] =do_normalize def _lowercase ( self ) -> Optional[int]: '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _lowercase ( self , lowerCAmelCase__=False , lowerCAmelCase__=False ) -> Any: '''simple docstring''' def _flatten(lowerCAmelCase__ ): return list(itertools.chain(*lowerCAmelCase__ ) ) if equal_length: a__ : str =floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size a__ : Union[str, Any] =[ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: a__ : List[Any] =[np.asarray(lowerCAmelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : int = ASTFeatureExtractor def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Optional[int] =ASTFeatureExtractionTester(self ) def _lowercase ( self ) -> str: '''simple docstring''' a__ : str =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 a__ : str =[floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] a__ : List[Any] =[np.asarray(lowerCAmelCase__ ) for speech_input in speech_inputs] # Test not batched input a__ : Dict =feat_extract(speech_inputs[0] , return_tensors="np" ).input_values a__ : Optional[int] =feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) ) # Test batched a__ : Any =feat_extract(lowerCAmelCase__ , padding=lowerCAmelCase__ , return_tensors="np" ).input_values a__ : str =feat_extract(lowerCAmelCase__ , padding=lowerCAmelCase__ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__ , lowerCAmelCase__ ): self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. a__ : str =[floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] a__ : Dict =np.asarray(lowerCAmelCase__ ) a__ : List[Any] =feat_extract(lowerCAmelCase__ , return_tensors="np" ).input_values a__ : Optional[int] =feat_extract(lowerCAmelCase__ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__ , lowerCAmelCase__ ): self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) ) @require_torch def _lowercase ( self ) -> int: '''simple docstring''' import torch a__ : Union[str, Any] =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) a__ : Tuple =np.random.rand(1_0_0 ).astype(np.floataa ) a__ : Any =np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: a__ : int =feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) a__ : List[str] =feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _lowercase ( self , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' from datasets import load_dataset a__ : int =load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech a__ : str =ds.sort("id" ).select(range(lowerCAmelCase__ ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] @require_torch def _lowercase ( self ) -> int: '''simple docstring''' a__ : Optional[Any] =torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on a__ : str =self._load_datasamples(1 ) a__ : Dict =ASTFeatureExtractor() a__ : str =feature_extractor(lowerCAmelCase__ , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 1_0_2_4, 1_2_8) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , lowerCAmelCase__ , atol=1E-4 ) )
95
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 ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = "arrow" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( split=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ , streaming=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : int =load_from_cache_file a__ : Tuple =file_format a__ : List[Any] =Spark( df=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , working_dir=lowerCAmelCase__ , **lowerCAmelCase__ , ) def _lowercase ( self ) -> str: '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) a__ : str =None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowerCAmelCase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
95
1
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
95
from math import pi def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): """simple docstring""" return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
95
1
def _A ( SCREAMING_SNAKE_CASE : int = 1 , SCREAMING_SNAKE_CASE : int = 1_000 ): """simple docstring""" a__ : Union[str, Any] =1 a__ : Any =0 for divide_by_number in range(SCREAMING_SNAKE_CASE , digit + 1 ): a__ : list[int] =[] a__ : Tuple =numerator for _ in range(1 , digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(SCREAMING_SNAKE_CASE ): a__ : Tuple =len(SCREAMING_SNAKE_CASE ) a__ : str =divide_by_number else: has_been_divided.append(SCREAMING_SNAKE_CASE ) a__ : Dict =now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
95
import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging UpperCAmelCase : int = { """cola""": 2, """mnli""": 3, """mrpc""": 2, """sst-2""": 2, """sts-b""": 1, """qqp""": 2, """qnli""": 2, """rte""": 2, """wnli""": 2, } logging.set_verbosity_info() def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any]=None ): """simple docstring""" a__ : Optional[int] =XLNetConfig.from_json_file(SCREAMING_SNAKE_CASE ) a__ : Dict =finetuning_task.lower() if finetuning_task is not None else "" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(f'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}''' ) a__ : List[str] =finetuning_task a__ : Tuple =GLUE_TASKS_NUM_LABELS[finetuning_task] a__ : List[Any] =XLNetForSequenceClassification(SCREAMING_SNAKE_CASE ) elif "squad" in finetuning_task: a__ : Optional[int] =finetuning_task a__ : Dict =XLNetForQuestionAnswering(SCREAMING_SNAKE_CASE ) else: a__ : List[Any] =XLNetLMHeadModel(SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Save pytorch-model a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : Dict =os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print(f'''Save PyTorch model to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE ) print(f'''Save configuration file to {os.path.abspath(SCREAMING_SNAKE_CASE )}''' ) with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--xlnet_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained XLNet model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the folder to store the PyTorch model or dataset/vocab.""", ) parser.add_argument( """--finetuning_task""", default=None, type=str, help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""", ) UpperCAmelCase : int = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
95
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] =size if size is not None else {"shortest_edge": 2_0} a__ : List[str] =crop_size if crop_size is not None else {"height": 1_8, "width": 1_8} a__ : Tuple =parent a__ : Union[str, Any] =batch_size a__ : List[str] =num_channels a__ : List[Any] =image_size a__ : str =min_resolution a__ : Optional[int] =max_resolution a__ : Tuple =do_resize a__ : Union[str, Any] =size a__ : List[Any] =do_center_crop a__ : List[str] =crop_size a__ : Optional[int] =do_flip_channel_order def _lowercase ( self ) -> Optional[int]: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : int = MobileViTImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : Tuple =MobileViTImageProcessingTester(self ) @property def _lowercase ( self ) -> List[str]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : str =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "size" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "center_crop" ) ) self.assertTrue(hasattr(lowerCAmelCase__ , "do_flip_channel_order" ) ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : List[Any] =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 2_0} ) self.assertEqual(image_processor.crop_size , {"height": 1_8, "width": 1_8} ) a__ : Union[str, Any] =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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' pass def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : 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 a__ : List[Any] =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : List[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input a__ : 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 a__ : int =image_processing(lowerCAmelCase__ , 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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : int =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input a__ : List[str] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a__ : List[str] =image_processing(lowerCAmelCase__ , 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"], ) , )
95
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { """google/canine-s""": """https://huggingface.co/google/canine-s/resolve/main/config.json""", # See all CANINE models at https://huggingface.co/models?filter=canine } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[Any] = """canine""" def __init__( self , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_6 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=0 , lowerCAmelCase__=0XE0_00 , lowerCAmelCase__=0XE0_01 , lowerCAmelCase__=4 , lowerCAmelCase__=4 , lowerCAmelCase__=8 , lowerCAmelCase__=1_6_3_8_4 , lowerCAmelCase__=1_2_8 , **lowerCAmelCase__ , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Optional[int] =max_position_embeddings a__ : str =hidden_size a__ : Optional[Any] =num_hidden_layers a__ : Tuple =num_attention_heads a__ : Optional[Any] =intermediate_size a__ : Optional[int] =hidden_act a__ : List[Any] =hidden_dropout_prob a__ : Union[str, Any] =attention_probs_dropout_prob a__ : Optional[Any] =initializer_range a__ : Union[str, Any] =type_vocab_size a__ : Optional[int] =layer_norm_eps # Character config: a__ : int =downsampling_rate a__ : Optional[Any] =upsampling_kernel_size a__ : Union[str, Any] =num_hash_functions a__ : Any =num_hash_buckets a__ : int =local_transformer_stride
95
1
def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" return credit_card_number.startswith(("34", "35", "37", "4", "5", "6") ) def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" a__ : Tuple =credit_card_number a__ : Union[str, Any] =0 a__ : List[str] =len(SCREAMING_SNAKE_CASE ) - 2 for i in range(SCREAMING_SNAKE_CASE , -1 , -2 ): # double the value of every second digit a__ : List[Any] =int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 a__ : List[str] =cc_number[:i] + str(SCREAMING_SNAKE_CASE ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(SCREAMING_SNAKE_CASE ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" a__ : List[Any] =f'''{credit_card_number} is an invalid credit card number because''' if not credit_card_number.isdigit(): print(f'''{error_message} it has nonnumerical characters.''' ) return False if not 13 <= len(SCREAMING_SNAKE_CASE ) <= 16: print(f'''{error_message} of its length.''' ) return False if not validate_initial_digits(SCREAMING_SNAKE_CASE ): print(f'''{error_message} of its first two digits.''' ) return False if not luhn_validation(SCREAMING_SNAKE_CASE ): print(f'''{error_message} it fails the Luhn check.''' ) return False print(f'''{credit_card_number} is a valid credit card number.''' ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number("""4111111111111111""") validate_credit_card_number("""32323""")
95
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device UpperCAmelCase : int = False class __lowerCAmelCase ( unittest.TestCase): pass @nightly @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Optional[Any] =torch.manual_seed(0 ) a__ : Optional[Any] =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCAmelCase__ ) a__ : str =VersatileDiffusionPipeline.from_pretrained(lowerCAmelCase__ , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] =generator.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] ="cyberpunk 2077" a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Union[str, Any] =torch.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images a__ : int =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : str ="A painting of a squirrel eating a burger " a__ : Optional[int] =torch.manual_seed(0 ) a__ : str =pipe.text_to_image( prompt=lowerCAmelCase__ , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" ).images a__ : Any =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Optional[int] =np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : Optional[Any] =pipe.image_variation(lowerCAmelCase__ , generator=lowerCAmelCase__ , output_type="numpy" ).images a__ : Union[str, Any] =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
95
1
import random from typing import Any def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" for _ in range(len(SCREAMING_SNAKE_CASE ) ): a__ : Dict =random.randint(0 , len(SCREAMING_SNAKE_CASE ) - 1 ) a__ : Optional[int] =random.randint(0 , len(SCREAMING_SNAKE_CASE ) - 1 ) a__ , a__ : List[Any] =data[b], data[a] return data if __name__ == "__main__": UpperCAmelCase : str = [0, 1, 2, 3, 4, 5, 6, 7] UpperCAmelCase : Dict = ["""python""", """says""", """hello""", """!"""] print("""Fisher-Yates Shuffle:""") print("""List""", integers, strings) print("""FY Shuffle""", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
95
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class __lowerCAmelCase : def _lowercase ( self , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError() def _lowercase ( self ) -> int: '''simple docstring''' raise NotImplementedError() class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , **lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : str =tokenizer a__ : List[str] =skip_prompt a__ : List[Any] =decode_kwargs # variables used in the streaming process a__ : Dict =[] a__ : int =0 a__ : str =True def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError("TextStreamer only supports batch size 1" ) elif len(value.shape ) > 1: a__ : Any =value[0] if self.skip_prompt and self.next_tokens_are_prompt: a__ : Dict =False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith("\n" ): a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 # If the last token is a CJK character, we print the characters. elif len(lowerCAmelCase__ ) > 0 and self._is_chinese_char(ord(text[-1] ) ): a__ : List[str] =text[self.print_len :] self.print_len += len(lowerCAmelCase__ ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: a__ : str =text[self.print_len : text.rfind(" " ) + 1] self.print_len += len(lowerCAmelCase__ ) self.on_finalized_text(lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' if len(self.token_cache ) > 0: a__ : Union[str, Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) a__ : List[Any] =text[self.print_len :] a__ : List[str] =[] a__ : Optional[int] =0 else: a__ : Union[str, Any] ="" a__ : Any =True self.on_finalized_text(lowerCAmelCase__ , stream_end=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> Optional[Any]: '''simple docstring''' print(lowerCAmelCase__ , flush=lowerCAmelCase__ , end="" if not stream_end else None ) def _lowercase ( self , lowerCAmelCase__ ) -> str: '''simple docstring''' if ( (cp >= 0X4E_00 and cp <= 0X9F_FF) or (cp >= 0X34_00 and cp <= 0X4D_BF) # or (cp >= 0X2_00_00 and cp <= 0X2_A6_DF) # or (cp >= 0X2_A7_00 and cp <= 0X2_B7_3F) # or (cp >= 0X2_B7_40 and cp <= 0X2_B8_1F) # or (cp >= 0X2_B8_20 and cp <= 0X2_CE_AF) # or (cp >= 0XF9_00 and cp <= 0XFA_FF) or (cp >= 0X2_F8_00 and cp <= 0X2_FA_1F) # ): # return True return False class __lowerCAmelCase ( UpperCamelCase__): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , lowerCAmelCase__ = None , **lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' super().__init__(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : str =Queue() a__ : Optional[Any] =None a__ : Any =timeout def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> List[str]: '''simple docstring''' self.text_queue.put(lowerCAmelCase__ , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self ) -> Dict: '''simple docstring''' return self def _lowercase ( self ) -> int: '''simple docstring''' a__ : int =self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
95
1
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger UpperCAmelCase : Optional[int] = get_logger(__name__) class __lowerCAmelCase ( enum.Enum): _lowercase : Dict = """all_checks""" _lowercase : int = """basic_checks""" _lowercase : Union[str, Any] = """no_checks""" class __lowerCAmelCase ( UpperCamelCase__): pass class __lowerCAmelCase ( UpperCamelCase__): pass class __lowerCAmelCase ( UpperCamelCase__): pass class __lowerCAmelCase ( UpperCamelCase__): pass def _A ( SCREAMING_SNAKE_CASE : Optional[dict] , SCREAMING_SNAKE_CASE : dict , SCREAMING_SNAKE_CASE : Union[str, Any]=None ): """simple docstring""" if expected_checksums is None: logger.info("Unable to verify checksums." ) return if len(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) ) if len(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) > 0: raise UnexpectedDownloadedFile(str(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) ) a__ : List[str] =[url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] a__ : Union[str, Any] =" for " + verification_name if verification_name is not None else "" if len(SCREAMING_SNAKE_CASE ) > 0: raise NonMatchingChecksumError( f'''Checksums didn\'t match{for_verification_name}:\n''' f'''{bad_urls}\n''' "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error" ) logger.info("All the checksums matched successfully" + for_verification_name ) class __lowerCAmelCase ( UpperCamelCase__): pass class __lowerCAmelCase ( UpperCamelCase__): pass class __lowerCAmelCase ( UpperCamelCase__): pass class __lowerCAmelCase ( UpperCamelCase__): pass def _A ( SCREAMING_SNAKE_CASE : Optional[dict] , SCREAMING_SNAKE_CASE : dict ): """simple docstring""" if expected_splits is None: logger.info("Unable to verify splits sizes." ) return if len(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) > 0: raise ExpectedMoreSplits(str(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) ) if len(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) > 0: raise UnexpectedSplits(str(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) ) a__ : Optional[Any] =[ {"expected": expected_splits[name], "recorded": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(SCREAMING_SNAKE_CASE ) > 0: raise NonMatchingSplitsSizesError(str(SCREAMING_SNAKE_CASE ) ) logger.info("All the splits matched successfully." ) def _A ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : bool = True ): """simple docstring""" if record_checksum: a__ : Tuple =shaaaa() with open(SCREAMING_SNAKE_CASE , "rb" ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , b"" ): m.update(SCREAMING_SNAKE_CASE ) a__ : str =m.hexdigest() else: a__ : Union[str, Any] =None return {"num_bytes": os.path.getsize(SCREAMING_SNAKE_CASE ), "checksum": checksum} def _A ( SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
95
def _A ( SCREAMING_SNAKE_CASE : int = 50 ): """simple docstring""" a__ : Any =[1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
95
1
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) UpperCAmelCase : Union[str, Any] = pytest.mark.integration @pytest.mark.parametrize("path" , ["paws", "csv"] ) def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : int ): """simple docstring""" inspect_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : str =path + ".py" assert script_name in os.listdir(SCREAMING_SNAKE_CASE ) assert "__pycache__" not in os.listdir(SCREAMING_SNAKE_CASE ) @pytest.mark.filterwarnings("ignore:inspect_metric is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.parametrize("path" , ["accuracy"] ) def _A ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : int ): """simple docstring""" inspect_metric(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) a__ : List[Any] =path + ".py" assert script_name in os.listdir(SCREAMING_SNAKE_CASE ) assert "__pycache__" not in os.listdir(SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( "path, config_name, expected_splits" , [ ("squad", "plain_text", ["train", "validation"]), ("dalle-mini/wit", "dalle-mini--wit", ["train"]), ("paws", "labeled_final", ["train", "test", "validation"]), ] , ) def _A ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" a__ : Union[str, Any] =get_dataset_config_info(SCREAMING_SNAKE_CASE , config_name=SCREAMING_SNAKE_CASE ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( "path, config_name, expected_exception" , [ ("paws", None, ValueError), ] , ) def _A ( SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : int ): """simple docstring""" with pytest.raises(SCREAMING_SNAKE_CASE ): get_dataset_config_info(SCREAMING_SNAKE_CASE , config_name=SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( "path, expected" , [ ("squad", "plain_text"), ("acronym_identification", "default"), ("lhoestq/squad", "plain_text"), ("lhoestq/test", "default"), ("lhoestq/demo1", "lhoestq--demo1"), ("dalle-mini/wit", "dalle-mini--wit"), ] , ) def _A ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" a__ : str =get_dataset_config_names(SCREAMING_SNAKE_CASE ) assert expected in config_names @pytest.mark.parametrize( "path, expected_configs, expected_splits_in_first_config" , [ ("squad", ["plain_text"], ["train", "validation"]), ("dalle-mini/wit", ["dalle-mini--wit"], ["train"]), ("paws", ["labeled_final", "labeled_swap", "unlabeled_final"], ["train", "test", "validation"]), ] , ) def _A ( SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" a__ : Optional[int] =get_dataset_infos(SCREAMING_SNAKE_CASE ) assert list(infos.keys() ) == expected_configs a__ : List[Any] =expected_configs[0] assert expected_config in infos a__ : Tuple =infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( "path, expected_config, expected_splits" , [ ("squad", "plain_text", ["train", "validation"]), ("dalle-mini/wit", "dalle-mini--wit", ["train"]), ("paws", "labeled_final", ["train", "test", "validation"]), ] , ) def _A ( SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" a__ : Union[str, Any] =get_dataset_infos(SCREAMING_SNAKE_CASE ) assert expected_config in infos a__ : Union[str, Any] =infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( "path, config_name, expected_exception" , [ ("paws", None, ValueError), ] , ) def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" with pytest.raises(SCREAMING_SNAKE_CASE ): get_dataset_split_names(SCREAMING_SNAKE_CASE , config_name=SCREAMING_SNAKE_CASE )
95
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if len(SCREAMING_SNAKE_CASE ) == 0: return [] a__ , a__ : int =min(SCREAMING_SNAKE_CASE ), max(SCREAMING_SNAKE_CASE ) a__ : Optional[int] =int(max_value - min_value ) + 1 a__ : list[list] =[[] for _ in range(SCREAMING_SNAKE_CASE )] for i in my_list: buckets[int(i - min_value )].append(SCREAMING_SNAKE_CASE ) return [v for bucket in buckets for v in sorted(SCREAMING_SNAKE_CASE )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
95
1
import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class __lowerCAmelCase ( UpperCamelCase__): _lowercase : int = 0 _lowercase : bool = False _lowercase : float = 3.0 class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {"a": 2} ) self.assertDictEqual(MockClass(a=2 , b=lowerCAmelCase__ ).to_kwargs() , {"a": 2, "b": True} ) self.assertDictEqual(MockClass(a=2 , c=2.25 ).to_kwargs() , {"a": 2, "c": 2.25} ) @require_cuda def _lowercase ( self ) -> str: '''simple docstring''' a__ : int =GradScalerKwargs(init_scale=1_0_2_4 , growth_factor=2 ) AcceleratorState._reset_state() a__ : List[str] =Accelerator(mixed_precision="fp16" , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) a__ : Optional[Any] =accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 10_24.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 2_0_0_0 ) self.assertEqual(scaler._enabled , lowerCAmelCase__ ) @require_multi_gpu def _lowercase ( self ) -> str: '''simple docstring''' a__ : List[Any] =["torchrun", F'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] execute_subprocess_async(lowerCAmelCase__ , env=os.environ.copy() ) if __name__ == "__main__": UpperCAmelCase : List[str] = DistributedDataParallelKwargs(bucket_cap_mb=15, find_unused_parameters=True) UpperCAmelCase : Optional[Any] = Accelerator(kwargs_handlers=[ddp_scaler]) UpperCAmelCase : str = torch.nn.Linear(100, 200) UpperCAmelCase : Dict = accelerator.prepare(model) # Check the values changed in kwargs UpperCAmelCase : int = """""" UpperCAmelCase : Union[str, Any] = model.bucket_bytes_cap // (1024 * 1024) if observed_bucket_cap_map != 15: error_msg += F"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += F"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += F"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += F"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += F"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
95
import numpy as np def _A ( SCREAMING_SNAKE_CASE : np.array ): """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
95
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = { """configuration_swinv2""": ["""SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Swinv2Config"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ """SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST""", """Swinv2ForImageClassification""", """Swinv2ForMaskedImageModeling""", """Swinv2Model""", """Swinv2PreTrainedModel""", ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys UpperCAmelCase : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
95
import numpy # List of input, output pairs UpperCAmelCase : str = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) UpperCAmelCase : Optional[int] = (((515, 22, 13), 555), ((61, 35, 49), 150)) UpperCAmelCase : str = [2, 4, 1, 5] UpperCAmelCase : List[str] = len(train_data) UpperCAmelCase : Dict = 0.0_0_9 def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Tuple="train" ): """simple docstring""" return calculate_hypothesis_value(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) - output( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : Tuple =0 for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _A ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : int=m ): """simple docstring""" a__ : Any =0 for i in range(SCREAMING_SNAKE_CASE ): if index == -1: summation_value += _error(SCREAMING_SNAKE_CASE ) else: summation_value += _error(SCREAMING_SNAKE_CASE ) * train_data[i][0][index] return summation_value def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Any =summation_of_cost_derivative(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) / m return cost_derivative_value def _A ( ): """simple docstring""" global parameter_vector # Tune these values to set a tolerance value for predicted output a__ : Dict =0.0_0_0_0_0_2 a__ : Union[str, Any] =0 a__ : Any =0 while True: j += 1 a__ : Any =[0, 0, 0, 0] for i in range(0 , len(SCREAMING_SNAKE_CASE ) ): a__ : Tuple =get_cost_derivative(i - 1 ) a__ : List[Any] =( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE , rtol=SCREAMING_SNAKE_CASE , ): break a__ : Optional[Any] =temp_parameter_vector print(("Number of iterations:", j) ) def _A ( ): """simple docstring""" for i in range(len(SCREAMING_SNAKE_CASE ) ): print(("Actual output value:", output(SCREAMING_SNAKE_CASE , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(SCREAMING_SNAKE_CASE , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("""\nTesting gradient descent for a linear hypothesis function.\n""") test_gradient_descent()
95
1
def _A ( SCREAMING_SNAKE_CASE : int = 3 , SCREAMING_SNAKE_CASE : int = 7 , SCREAMING_SNAKE_CASE : int = 1_000_000 ): """simple docstring""" a__ : List[str] =0 a__ : Dict =1 for current_denominator in range(1 , limit + 1 ): a__ : Union[str, Any] =current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: a__ : Any =current_numerator a__ : Tuple =current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
95
def _A ( SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" a__ : Optional[Any] =len(SCREAMING_SNAKE_CASE ) while cur > 1: # Find the maximum number in arr a__ : List[Any] =arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi a__ : int =arr[mi::-1] + arr[mi + 1 : len(SCREAMING_SNAKE_CASE )] # Reverse whole list a__ : List[str] =arr[cur - 1 :: -1] + arr[cur : len(SCREAMING_SNAKE_CASE )] cur -= 1 return arr if __name__ == "__main__": UpperCAmelCase : int = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase : Optional[int] = [int(item) for item in user_input.split(""",""")] print(pancake_sort(unsorted))
95
1
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device UpperCAmelCase : int = False class __lowerCAmelCase ( unittest.TestCase): pass @nightly @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Optional[Any] =torch.manual_seed(0 ) a__ : Optional[Any] =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCAmelCase__ ) a__ : str =VersatileDiffusionPipeline.from_pretrained(lowerCAmelCase__ , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] =generator.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt="first prompt" , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def _lowercase ( self ) -> Any: '''simple docstring''' a__ : str =VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) a__ : Optional[Any] ="cyberpunk 2077" a__ : int =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) a__ : Union[str, Any] =torch.manual_seed(0 ) a__ : Tuple =pipe.dual_guided( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , text_to_image_strength=0.75 , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" , ).images a__ : int =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : str ="A painting of a squirrel eating a burger " a__ : Optional[int] =torch.manual_seed(0 ) a__ : str =pipe.text_to_image( prompt=lowerCAmelCase__ , generator=lowerCAmelCase__ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type="numpy" ).images a__ : Any =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Optional[int] =np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 a__ : Optional[Any] =pipe.image_variation(lowerCAmelCase__ , generator=lowerCAmelCase__ , output_type="numpy" ).images a__ : Union[str, Any] =image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any =np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
95
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class __lowerCAmelCase ( unittest.TestCase): def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Any =tempfile.mkdtemp() # fmt: off a__ : List[Any] =["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on a__ : str =dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) a__ : List[Any] =["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""] a__ : Optional[int] ={"unk_token": "<unk>"} a__ : Optional[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) a__ : Tuple =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowerCAmelCase__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(lowerCAmelCase__ ) ) a__ : Optional[Any] ={ "do_resize": True, "size": 2_0, "do_center_crop": True, "crop_size": 1_8, "do_normalize": True, "image_mean": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], "image_std": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } a__ : Dict =os.path.join(self.tmpdirname , lowerCAmelCase__ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self , **lowerCAmelCase__ ) -> Any: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[Any] =[np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] a__ : List[Any] =[Image.fromarray(np.moveaxis(lowerCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Union[str, Any] =self.get_tokenizer() a__ : int =self.get_rust_tokenizer() a__ : List[str] =self.get_image_processor() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) a__ : Optional[Any] =CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=lowerCAmelCase__ ) a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) a__ : Dict =CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor , lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : List[str] =CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a__ : str =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) a__ : int =self.get_image_processor(do_normalize=lowerCAmelCase__ , padding_value=1.0 ) a__ : Optional[Any] =CLIPSegProcessor.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 _lowercase ( self ) -> List[Any]: '''simple docstring''' a__ : str =self.get_image_processor() a__ : Optional[int] =self.get_tokenizer() a__ : Dict =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : str =self.prepare_image_inputs() a__ : Any =image_processor(lowerCAmelCase__ , return_tensors="np" ) a__ : Optional[int] =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 _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : List[Any] =self.get_tokenizer() a__ : Optional[int] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Union[str, Any] ="lower newer" a__ : List[str] =processor(text=lowerCAmelCase__ ) a__ : str =tokenizer(lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Any =self.get_image_processor() a__ : Dict =self.get_tokenizer() a__ : Union[str, Any] =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict ="lower newer" a__ : int =self.prepare_image_inputs() a__ : Any =processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> str: '''simple docstring''' a__ : Union[str, Any] =self.get_image_processor() a__ : Optional[Any] =self.get_tokenizer() a__ : str =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : int =self.prepare_image_inputs() a__ : Union[str, Any] =self.prepare_image_inputs() a__ : Tuple =processor(images=lowerCAmelCase__ , visual_prompt=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "conditional_pixel_values"] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =self.get_image_processor() a__ : Any =self.get_tokenizer() a__ : Tuple =CLIPSegProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) a__ : Dict =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a__ : Optional[Any] =processor.batch_decode(lowerCAmelCase__ ) a__ : Dict =tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
95
1