

import collections
import inspect
import unittest

from transformers import SwinvaConfig
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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
					from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor






class        A_		:
							def __init__(		self		:			List[Any]   ,SCREAMING_SNAKE_CASE__		:			List[str]   ,SCREAMING_SNAKE_CASE__		:			List[str]=1_3   ,SCREAMING_SNAKE_CASE__		:			List[str]=3_2   ,SCREAMING_SNAKE_CASE__		:			Tuple=2   ,SCREAMING_SNAKE_CASE__		:			str=3   ,SCREAMING_SNAKE_CASE__		:			Union[str, Any]=1_6   ,SCREAMING_SNAKE_CASE__		:			List[str]=[1, 2, 1]   ,SCREAMING_SNAKE_CASE__		:			Tuple=[2, 2, 4]   ,SCREAMING_SNAKE_CASE__		:			Dict=2   ,SCREAMING_SNAKE_CASE__		:			List[Any]=2.0   ,SCREAMING_SNAKE_CASE__		:			Dict=True   ,SCREAMING_SNAKE_CASE__		:			Tuple=0.0   ,SCREAMING_SNAKE_CASE__		:			Dict=0.0   ,SCREAMING_SNAKE_CASE__		:			Optional[int]=0.1   ,SCREAMING_SNAKE_CASE__		:			Union[str, Any]="gelu"   ,SCREAMING_SNAKE_CASE__		:			str=False   ,SCREAMING_SNAKE_CASE__		:			str=True   ,SCREAMING_SNAKE_CASE__		:			Dict=0.02   ,SCREAMING_SNAKE_CASE__		:			Union[str, Any]=1E-5   ,SCREAMING_SNAKE_CASE__		:			Dict=True   ,SCREAMING_SNAKE_CASE__		:			Any=None   ,SCREAMING_SNAKE_CASE__		:			List[str]=True   ,SCREAMING_SNAKE_CASE__		:			List[str]=1_0   ,SCREAMING_SNAKE_CASE__		:			Optional[int]=8   ,):
								__lowerCamelCase				:				Optional[int]					       = parent
								__lowerCamelCase				:				Union[str, Any]					       = batch_size
								__lowerCamelCase				:				List[Any]					       = image_size
								__lowerCamelCase				:				Optional[Any]					       = patch_size
								__lowerCamelCase				:				int					       = num_channels
								__lowerCamelCase				:				Dict					       = embed_dim
								__lowerCamelCase				:				List[Any]					       = depths
								__lowerCamelCase				:				Optional[Any]					       = num_heads
								__lowerCamelCase				:				Tuple					       = window_size
								__lowerCamelCase				:				Tuple					       = mlp_ratio
								__lowerCamelCase				:				Dict					       = qkv_bias
								__lowerCamelCase				:				int					       = hidden_dropout_prob
								__lowerCamelCase				:				List[Any]					       = attention_probs_dropout_prob
								__lowerCamelCase				:				Tuple					       = drop_path_rate
								__lowerCamelCase				:				str					       = hidden_act
								__lowerCamelCase				:				Optional[Any]					       = use_absolute_embeddings
								__lowerCamelCase				:				str					       = patch_norm
								__lowerCamelCase				:				Optional[int]					       = layer_norm_eps
								__lowerCamelCase				:				Optional[Any]					       = initializer_range
								__lowerCamelCase				:				int					       = is_training
								__lowerCamelCase				:				str					       = scope
								__lowerCamelCase				:				int					       = use_labels
								__lowerCamelCase				:				int					       = type_sequence_label_size
								__lowerCamelCase				:				int					       = encoder_stride
							def     lowerCAmelCase     (		self		:			Optional[Any]):
								__lowerCamelCase				:				Union[str, Any]					       = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

								__lowerCamelCase				:				int					       = None
								if self.use_labels:
									__lowerCamelCase				:				Optional[Any]					       = ids_tensor([self.batch_size]   ,self.type_sequence_label_size)

								__lowerCamelCase				:				Union[str, Any]					       = self.get_config()

								return config, pixel_values, labels
							def     lowerCAmelCase     (		self		:			int):
								return SwinvaConfig(
								    image_size=self.image_size   ,patch_size=self.patch_size   ,num_channels=self.num_channels   ,embed_dim=self.embed_dim   ,depths=self.depths   ,num_heads=self.num_heads   ,window_size=self.window_size   ,mlp_ratio=self.mlp_ratio   ,qkv_bias=self.qkv_bias   ,hidden_dropout_prob=self.hidden_dropout_prob   ,attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,drop_path_rate=self.drop_path_rate   ,hidden_act=self.hidden_act   ,use_absolute_embeddings=self.use_absolute_embeddings   ,path_norm=self.patch_norm   ,layer_norm_eps=self.layer_norm_eps   ,initializer_range=self.initializer_range   ,encoder_stride=self.encoder_stride   ,)
							def     lowerCAmelCase     (		self		:			List[str]   ,SCREAMING_SNAKE_CASE__		:			Tuple   ,SCREAMING_SNAKE_CASE__		:			Any   ,SCREAMING_SNAKE_CASE__		:			str):
								__lowerCamelCase				:				Tuple					       = SwinvaModel(config=SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()
								__lowerCamelCase				:				Tuple					       = model(SCREAMING_SNAKE_CASE__)

								__lowerCamelCase				:				Any					       = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1))
								__lowerCamelCase				:				List[str]					       = int(config.embed_dim * 2 ** (len(config.depths) - 1))

								self.parent.assertEqual(result.last_hidden_state.shape   ,(self.batch_size, expected_seq_len, expected_dim))
							def     lowerCAmelCase     (		self		:			Union[str, Any]   ,SCREAMING_SNAKE_CASE__		:			int   ,SCREAMING_SNAKE_CASE__		:			List[Any]   ,SCREAMING_SNAKE_CASE__		:			Optional[Any]):
								__lowerCamelCase				:				List[str]					       = SwinvaForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()
								__lowerCamelCase				:				Optional[int]					       = model(SCREAMING_SNAKE_CASE__)
								self.parent.assertEqual(
								    result.logits.shape   ,(self.batch_size, self.num_channels, self.image_size, self.image_size))

								# test greyscale images
								__lowerCamelCase				:				Tuple					       = 1
								__lowerCamelCase				:				Union[str, Any]					       = SwinvaForMaskedImageModeling(SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()

								__lowerCamelCase				:				str					       = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
								__lowerCamelCase				:				Dict					       = model(SCREAMING_SNAKE_CASE__)
								self.parent.assertEqual(result.logits.shape   ,(self.batch_size, 1, self.image_size, self.image_size))
							def     lowerCAmelCase     (		self		:			List[Any]   ,SCREAMING_SNAKE_CASE__		:			Optional[int]   ,SCREAMING_SNAKE_CASE__		:			str   ,SCREAMING_SNAKE_CASE__		:			str):
								__lowerCamelCase				:				Optional[Any]					       = self.type_sequence_label_size
								__lowerCamelCase				:				Optional[int]					       = SwinvaForImageClassification(SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()
								__lowerCamelCase				:				int					       = model(SCREAMING_SNAKE_CASE__   ,labels=SCREAMING_SNAKE_CASE__)
								self.parent.assertEqual(result.logits.shape   ,(self.batch_size, self.type_sequence_label_size))


							def     lowerCAmelCase     (		self		:			Optional[int]):
								__lowerCamelCase				:				Any					       = self.prepare_config_and_inputs()
								__lowerCamelCase       , __lowerCamelCase       , __lowerCamelCase				:				Union[str, Any]					       = config_and_inputs
								__lowerCamelCase				:				int					       = {'pixel_values': pixel_values}
								return config, inputs_dict






@require_torch
class        A_		(       SCREAMING_SNAKE_CASE			,							SCREAMING_SNAKE_CASE			,							unittest.TestCase				):
							_UpperCAmelCase    :  Optional[Any]						      =      (
							    (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
							)
							_UpperCAmelCase    :  Tuple						      =      (
							    {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification}
							    if is_torch_available()
							    else {}
							)

							_UpperCAmelCase    :  Dict						      =      False
							_UpperCAmelCase    :  List[Any]						      =      False
							_UpperCAmelCase    :  Union[str, Any]						      =      False
							_UpperCAmelCase    :  Any						      =      False
							def     lowerCAmelCase     (		self		:			Union[str, Any]):
								__lowerCamelCase				:				List[Any]					       = SwinvaModelTester(self)
								__lowerCamelCase				:				Optional[int]					       = ConfigTester(self   ,config_class=SCREAMING_SNAKE_CASE__   ,embed_dim=3_7)
							def     lowerCAmelCase     (		self		:			int):
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()
							def     lowerCAmelCase     (		self		:			Any):
								__lowerCamelCase				:				Tuple					       = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__)
							@unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.')
							def     lowerCAmelCase     (		self		:			Tuple):
								pass
							@unittest.skip(reason='Swinv2 does not use inputs_embeds')
							def     lowerCAmelCase     (		self		:			Optional[Any]):
								pass
							def     lowerCAmelCase     (		self		:			Any):
								__lowerCamelCase       , __lowerCamelCase				:				str					       = self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									__lowerCamelCase				:				Optional[Any]					       = model_class(SCREAMING_SNAKE_CASE__)
									self.assertIsInstance(model.get_input_embeddings()   ,(nn.Module))
									__lowerCamelCase				:				List[str]					       = model.get_output_embeddings()
									self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__   ,nn.Linear))
							def     lowerCAmelCase     (		self		:			str):
								__lowerCamelCase       , __lowerCamelCase				:				str					       = self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									__lowerCamelCase				:				Optional[Any]					       = model_class(SCREAMING_SNAKE_CASE__)
									__lowerCamelCase				:				Union[str, Any]					       = inspect.signature(model.forward)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									__lowerCamelCase				:				Optional[Any]					       = [*signature.parameters.keys()]

									__lowerCamelCase				:				List[Any]					       = ['pixel_values']
									self.assertListEqual(arg_names[:1]   ,SCREAMING_SNAKE_CASE__)
							def     lowerCAmelCase     (		self		:			List[Any]):
								__lowerCamelCase       , __lowerCamelCase				:				Any					       = self.model_tester.prepare_config_and_inputs_for_common()
								__lowerCamelCase				:				Tuple					       = True

								for model_class in self.all_model_classes:
									__lowerCamelCase				:				str					       = True
									__lowerCamelCase				:				List[str]					       = False
									__lowerCamelCase				:				List[str]					       = True
									__lowerCamelCase				:				List[str]					       = model_class(SCREAMING_SNAKE_CASE__)
									model.to(SCREAMING_SNAKE_CASE__)
									model.eval()
									with torch.no_grad():
										__lowerCamelCase				:				Union[str, Any]					       = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__))
									__lowerCamelCase				:				Optional[Any]					       = outputs.attentions
									__lowerCamelCase				:				Tuple					       = len(self.model_tester.depths)
									self.assertEqual(len(SCREAMING_SNAKE_CASE__)   ,SCREAMING_SNAKE_CASE__)

									# check that output_attentions also work using config
									del inputs_dict["output_attentions"]
									__lowerCamelCase				:				Dict					       = True
									__lowerCamelCase				:				int					       = config.window_size**2
									__lowerCamelCase				:				List[str]					       = model_class(SCREAMING_SNAKE_CASE__)
									model.to(SCREAMING_SNAKE_CASE__)
									model.eval()
									with torch.no_grad():
										__lowerCamelCase				:				str					       = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__))
									__lowerCamelCase				:				Optional[Any]					       = outputs.attentions
									self.assertEqual(len(SCREAMING_SNAKE_CASE__)   ,SCREAMING_SNAKE_CASE__)

									self.assertListEqual(
									    list(attentions[0].shape[-3:])   ,[self.model_tester.num_heads[0], window_size_squared, window_size_squared]   ,)
									__lowerCamelCase				:				Dict					       = len(SCREAMING_SNAKE_CASE__)

									# Check attention is always last and order is fine
									__lowerCamelCase				:				Optional[Any]					       = True
									__lowerCamelCase				:				List[Any]					       = True
									__lowerCamelCase				:				Tuple					       = model_class(SCREAMING_SNAKE_CASE__)
									model.to(SCREAMING_SNAKE_CASE__)
									model.eval()
									with torch.no_grad():
										__lowerCamelCase				:				Tuple					       = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__))

									if hasattr(self.model_tester   ,'num_hidden_states_types'):
										__lowerCamelCase				:				int					       = self.model_tester.num_hidden_states_types
									else:
										# also another +1 for reshaped_hidden_states
										__lowerCamelCase				:				List[str]					       = 2
									self.assertEqual(out_len + added_hidden_states   ,len(SCREAMING_SNAKE_CASE__))

									__lowerCamelCase				:				Optional[Any]					       = outputs.attentions

									self.assertEqual(len(SCREAMING_SNAKE_CASE__)   ,SCREAMING_SNAKE_CASE__)

									self.assertListEqual(
									    list(self_attentions[0].shape[-3:])   ,[self.model_tester.num_heads[0], window_size_squared, window_size_squared]   ,)
							def     lowerCAmelCase     (		self		:			Dict   ,SCREAMING_SNAKE_CASE__		:			str   ,SCREAMING_SNAKE_CASE__		:			Union[str, Any]   ,SCREAMING_SNAKE_CASE__		:			List[str]   ,SCREAMING_SNAKE_CASE__		:			Any):
								__lowerCamelCase				:				int					       = model_class(SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()

								with torch.no_grad():
									__lowerCamelCase				:				Dict					       = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__))

								__lowerCamelCase				:				Dict					       = outputs.hidden_states

								__lowerCamelCase				:				List[str]					       = getattr(
								    self.model_tester   ,'expected_num_hidden_layers'   ,len(self.model_tester.depths) + 1)
								self.assertEqual(len(SCREAMING_SNAKE_CASE__)   ,SCREAMING_SNAKE_CASE__)

								# Swinv2 has a different seq_length
								__lowerCamelCase				:				Optional[Any]					       = (
								    config.patch_size
								    if isinstance(config.patch_size   ,collections.abc.Iterable)
								    else (config.patch_size, config.patch_size)
								)

								__lowerCamelCase				:				int					       = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

								self.assertListEqual(
								    list(hidden_states[0].shape[-2:])   ,[num_patches, self.model_tester.embed_dim]   ,)

								__lowerCamelCase				:				int					       = outputs.reshaped_hidden_states
								self.assertEqual(len(SCREAMING_SNAKE_CASE__)   ,SCREAMING_SNAKE_CASE__)

								__lowerCamelCase       , __lowerCamelCase       , __lowerCamelCase       , __lowerCamelCase				:				Tuple					       = reshaped_hidden_states[0].shape
								__lowerCamelCase				:				Union[str, Any]					       = (
								    reshaped_hidden_states[0].view(SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__   ,height * width).permute(0   ,2   ,1)
								)
								self.assertListEqual(
								    list(reshaped_hidden_states.shape[-2:])   ,[num_patches, self.model_tester.embed_dim]   ,)
							def     lowerCAmelCase     (		self		:			Union[str, Any]):
								__lowerCamelCase       , __lowerCamelCase				:				List[str]					       = self.model_tester.prepare_config_and_inputs_for_common()

								__lowerCamelCase				:				int					       = (
								    self.model_tester.image_size
								    if isinstance(self.model_tester.image_size   ,collections.abc.Iterable)
								    else (self.model_tester.image_size, self.model_tester.image_size)
								)

								for model_class in self.all_model_classes:
									__lowerCamelCase				:				List[Any]					       = True
									self.check_hidden_states_output(SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									__lowerCamelCase				:				Optional[int]					       = True

									self.check_hidden_states_output(SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__)
							def     lowerCAmelCase     (		self		:			Union[str, Any]):
								__lowerCamelCase       , __lowerCamelCase				:				List[Any]					       = self.model_tester.prepare_config_and_inputs_for_common()
								__lowerCamelCase				:				int					       = 3

								__lowerCamelCase				:				List[str]					       = (
								    self.model_tester.image_size
								    if isinstance(self.model_tester.image_size   ,collections.abc.Iterable)
								    else (self.model_tester.image_size, self.model_tester.image_size)
								)
								__lowerCamelCase				:				Tuple					       = (
								    config.patch_size
								    if isinstance(config.patch_size   ,collections.abc.Iterable)
								    else (config.patch_size, config.patch_size)
								)

								__lowerCamelCase				:				List[Any]					       = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
								__lowerCamelCase				:				Optional[int]					       = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

								for model_class in self.all_model_classes:
									__lowerCamelCase				:				str					       = True
									self.check_hidden_states_output(SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__   ,(padded_height, padded_width))

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									__lowerCamelCase				:				List[Any]					       = True
									self.check_hidden_states_output(SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__   ,(padded_height, padded_width))
							def     lowerCAmelCase     (		self		:			int):
								__lowerCamelCase				:				Any					       = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__)
							def     lowerCAmelCase     (		self		:			List[Any]):
								__lowerCamelCase				:				int					       = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__)
							@slow
							def     lowerCAmelCase     (		self		:			Optional[int]):
								for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__lowerCamelCase				:				Optional[int]					       = SwinvaModel.from_pretrained(SCREAMING_SNAKE_CASE__)
									self.assertIsNotNone(SCREAMING_SNAKE_CASE__)


							def     lowerCAmelCase     (		self		:			str):
								__lowerCamelCase       , __lowerCamelCase				:				List[Any]					       = self.model_tester.prepare_config_and_inputs_for_common()

								__lowerCamelCase				:				int					       = _config_zero_init(SCREAMING_SNAKE_CASE__)
								for model_class in self.all_model_classes:
									__lowerCamelCase				:				List[Any]					       = model_class(config=SCREAMING_SNAKE_CASE__)
									for name, param in model.named_parameters():
										if "embeddings" not in name and "logit_scale" not in name and param.requires_grad:
											self.assertIn(
											    ((param.data.mean() * 1E9).round() / 1E9).item()   ,[0.0, 1.0]   ,msg=F"Parameter {name} of model {model_class} seems not properly initialized"   ,)






@require_vision
@require_torch
class        A_		(       unittest.TestCase				):
							@cached_property
							def     lowerCAmelCase     (		self		:			str):
								return (
								    AutoImageProcessor.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256')
								    if is_vision_available()
								    else None
								)


							@slow
							def     lowerCAmelCase     (		self		:			str):
								__lowerCamelCase				:				List[str]					       = SwinvaForImageClassification.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256').to(
								    SCREAMING_SNAKE_CASE__)
								__lowerCamelCase				:				List[Any]					       = self.default_image_processor

								__lowerCamelCase				:				Optional[Any]					       = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
								__lowerCamelCase				:				List[str]					       = image_processor(images=SCREAMING_SNAKE_CASE__   ,return_tensors='pt').to(SCREAMING_SNAKE_CASE__)

								# forward pass
								with torch.no_grad():
									__lowerCamelCase				:				List[str]					       = model(**SCREAMING_SNAKE_CASE__)

								# verify the logits
								__lowerCamelCase				:				Tuple					       = torch.Size((1, 1_0_0_0))
								self.assertEqual(outputs.logits.shape   ,SCREAMING_SNAKE_CASE__)
								__lowerCamelCase				:				Optional[Any]					       = torch.tensor([-0.3947, -0.4306, 0.0026]).to(SCREAMING_SNAKE_CASE__)
								self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,SCREAMING_SNAKE_CASE__   ,atol=1E-4))








# flake8: noqa
# Lint as: python3

from typing import Dict, List, Optional, Type

from .. import config
from ..utils import logging
from .formatting import (
    ArrowFormatter,
    CustomFormatter,
    Formatter,
    PandasFormatter,
    PythonFormatter,
    TensorFormatter,
    format_table,
    query_table,
)
from .np_formatter import NumpyFormatter


lowerCAmelCase__      		= logging.get_logger(__name__)

lowerCAmelCase__      		= {}
lowerCAmelCase__      		= {}
lowerCAmelCase__      		= {}
def 							_UpperCAmelCase				(UpperCamelCase__     :  type				,							UpperCamelCase__     :  Optional[str]				,							UpperCamelCase__     :  Optional[List[str]] = None				,							):
       _A      :       Union[str, Any]				    = aliases if aliases is not None else []
       if format_type in _FORMAT_TYPES:
              logger.warning(
                  f"Overwriting format type '{format_type}' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})"						)
       _A      :       Dict				    = formatter_cls
       for alias in set(aliases + [format_type]						):
              if alias in _FORMAT_TYPES_ALIASES:
                     logger.warning(
                         f"Overwriting format type alias '{alias}' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})"						)
              _A      :       Dict				    = format_type
def 							_UpperCAmelCase				(UpperCamelCase__     :  Exception				,							UpperCamelCase__     :  Optional[str]				,							UpperCamelCase__     :  Optional[List[str]] = None						):
       _A      :       Union[str, Any]				    = aliases if aliases is not None else []
       for alias in set(aliases + [format_type]						):
              _A      :       Union[str, Any]				    = unavailable_error


# Here we define all the available formatting functions that can be used by `Dataset.set_format`
_register_formatter(PythonFormatter, None, aliases=['python'])
_register_formatter(ArrowFormatter, 'arrow', aliases=['pa', 'pyarrow'])
_register_formatter(NumpyFormatter, 'numpy', aliases=['np'])
_register_formatter(PandasFormatter, 'pandas', aliases=['pd'])
_register_formatter(CustomFormatter, 'custom')

if config.TORCH_AVAILABLE:
    from .torch_formatter import TorchFormatter

    _register_formatter(TorchFormatter, 'torch', aliases=['pt', 'pytorch'])
else:
    lowerCAmelCase__      		= ValueError('PyTorch needs to be installed to be able to return PyTorch tensors.')
    _register_unavailable_formatter(_torch_error, 'torch', aliases=['pt', 'pytorch'])

if config.TF_AVAILABLE:
    from .tf_formatter import TFFormatter

    _register_formatter(TFFormatter, 'tensorflow', aliases=['tf'])
else:
    lowerCAmelCase__      		= ValueError('Tensorflow needs to be installed to be able to return Tensorflow tensors.')
    _register_unavailable_formatter(_tf_error, 'tensorflow', aliases=['tf'])

if config.JAX_AVAILABLE:
    from .jax_formatter import JaxFormatter

    _register_formatter(JaxFormatter, 'jax', aliases=[])
else:
    lowerCAmelCase__      		= ValueError('JAX needs to be installed to be able to return JAX arrays.')
    _register_unavailable_formatter(_jax_error, 'jax', aliases=[])
def 							_UpperCAmelCase				(UpperCamelCase__     :  Optional[str]						):
       if format_type in _FORMAT_TYPES_ALIASES:
              return _FORMAT_TYPES_ALIASES[format_type]
       else:
              return format_type






def 							_UpperCAmelCase				(UpperCamelCase__     :  Optional[str]				,							**UpperCamelCase__     :  List[Any]						):
       _A      :       List[str]				    = get_format_type_from_alias(UpperCamelCase__						)
       if format_type in _FORMAT_TYPES:
              return _FORMAT_TYPES[format_type](**UpperCamelCase__						)
       if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE:
              raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type]
       else:
              raise ValueError(
                  f"Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None						)}, but got '{format_type}'"						)
