






"""simple docstring"""





import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
							import jax
							import jax.numpy as jnp

							from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor



class       __A		(   unittest.TestCase			):

					def __init__(			self  :      Optional[Any]     ,		__snake_case  :      str     ,		__snake_case  :      Union[str, Any]=3     ,		__snake_case  :      Tuple=3_2     ,		__snake_case  :      List[str]=3     ,		__snake_case  :      Tuple=1_0     ,		__snake_case  :      str=[1_0, 2_0, 3_0, 4_0]     ,		__snake_case  :      Any=[1, 1, 2, 1]     ,		__snake_case  :      Optional[Any]=True     ,		__snake_case  :      Tuple=True     ,		__snake_case  :      Any="relu"     ,		__snake_case  :      Dict=3     ,		__snake_case  :      Tuple=None     ,		)			->							Optional[int]:
											__magic_name__:	str							=       parent
											__magic_name__:	Optional[Any]							=       batch_size
											__magic_name__:	Any							=       image_size
											__magic_name__:	str							=       num_channels
											__magic_name__:	Union[str, Any]							=       embeddings_size
											__magic_name__:	List[Any]							=       hidden_sizes
											__magic_name__:	Optional[Any]							=       depths
											__magic_name__:	List[Any]							=       is_training
											__magic_name__:	Union[str, Any]							=       use_labels
											__magic_name__:	Optional[Any]							=       hidden_act
											__magic_name__:	Dict							=       num_labels
											__magic_name__:	Union[str, Any]							=       scope
											__magic_name__:	Dict							=       len(__snake_case					)

					def   lowerCamelCase__   (			self  :      Optional[Any]					)			->							int:
											__magic_name__:	Optional[int]							=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

											__magic_name__:	Dict							=       self.get_config()

											return config, pixel_values

					def   lowerCamelCase__   (			self  :      Optional[Any]					)			->							List[str]:
											return RegNetConfig(
											    num_channels=self.num_channels     ,		embeddings_size=self.embeddings_size     ,		hidden_sizes=self.hidden_sizes     ,		depths=self.depths     ,		hidden_act=self.hidden_act     ,		num_labels=self.num_labels     ,		image_size=self.image_size     ,		)

					def   lowerCamelCase__   (			self  :      Union[str, Any]     ,		__snake_case  :      Any     ,		__snake_case  :      str					)			->							Union[str, Any]:
											__magic_name__:	int							=       FlaxRegNetModel(config=__snake_case					)
											__magic_name__:	Optional[int]							=       model(__snake_case					)

											# Output shape (b, c, h, w)
											self.parent.assertEqual(
											    result.last_hidden_state.shape     ,		(self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)     ,		)

					def   lowerCamelCase__   (			self  :      List[str]     ,		__snake_case  :      str     ,		__snake_case  :      Optional[int]					)			->							List[str]:
											__magic_name__:	List[str]							=       self.num_labels
											__magic_name__:	Dict							=       FlaxRegNetForImageClassification(config=__snake_case					)
											__magic_name__:	Optional[int]							=       model(__snake_case					)
											self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.num_labels)					)






					def   lowerCamelCase__   (			self  :      Union[str, Any]					)			->							Optional[int]:
											__magic_name__:	int							=       self.prepare_config_and_inputs()
											__magic_name__,			__magic_name__:	List[Any]							=       config_and_inputs
											__magic_name__:	Tuple							=       {"""pixel_values""": pixel_values}
											return config, inputs_dict



@require_flax
class       __A		(   SCREAMING_SNAKE_CASE_     ,unittest.TestCase			):
					UpperCAmelCase__								=				(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

					UpperCAmelCase__								=				False
					UpperCAmelCase__								=				False
					UpperCAmelCase__								=				False

					def   lowerCamelCase__   (			self  :      int					)			->							None:
											__magic_name__:	str							=       FlaxRegNetModelTester(self					)
											__magic_name__:	List[str]							=       ConfigTester(self     ,		config_class=__snake_case     ,		has_text_modality=__snake_case					)

					def   lowerCamelCase__   (			self  :      Tuple					)			->							Optional[int]:
											self.create_and_test_config_common_properties()
											self.config_tester.create_and_test_config_to_json_string()
											self.config_tester.create_and_test_config_to_json_file()
											self.config_tester.create_and_test_config_from_and_save_pretrained()
											self.config_tester.create_and_test_config_with_num_labels()
											self.config_tester.check_config_can_be_init_without_params()
											self.config_tester.check_config_arguments_init()

					def   lowerCamelCase__   (			self  :      List[Any]					)			->							Union[str, Any]:
											return

					def   lowerCamelCase__   (			self  :      Union[str, Any]					)			->							Optional[Any]:
											__magic_name__:	Any							=       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__snake_case					)

					def   lowerCamelCase__   (			self  :      int					)			->							List[str]:
											__magic_name__:	Tuple							=       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__snake_case					)

					@unittest.skip(reason="""RegNet does not use inputs_embeds"""					)
					def   lowerCamelCase__   (			self  :      Optional[int]					)			->							str:
											pass

					@unittest.skip(reason="""RegNet does not support input and output embeddings"""					)
					def   lowerCamelCase__   (			self  :      Dict					)			->							int:
											pass

					def   lowerCamelCase__   (			self  :      Tuple					)			->							int:
											__magic_name__,			__magic_name__:	Dict							=       self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	__magic_name__:	Any							=       model_class(__snake_case					)
																	__magic_name__:	List[Any]							=       inspect.signature(model.__call__					)
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	__magic_name__:	Union[str, Any]							=       [*signature.parameters.keys()]

																	__magic_name__:	Optional[int]							=       ["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]     ,		__snake_case					)

					def   lowerCamelCase__   (			self  :      Optional[int]					)			->							int:
											def check_hidden_states_output(__snake_case  :      Any     ,		__snake_case  :      Optional[int]     ,		__snake_case  :      Optional[int]					):
																	__magic_name__:	int							=       model_class(__snake_case					)

																	__magic_name__:	Optional[Any]							=       model(**self._prepare_for_class(__snake_case     ,		__snake_case					)					)

																	__magic_name__:	List[str]							=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																	__magic_name__:	Union[str, Any]							=       self.model_tester.num_stages
																	self.assertEqual(len(__snake_case					)     ,		expected_num_stages + 1					)

											__magic_name__,			__magic_name__:	Union[str, Any]							=       self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	__magic_name__:	int							=       True
																	check_hidden_states_output(__snake_case     ,		__snake_case     ,		__snake_case					)

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

																	check_hidden_states_output(__snake_case     ,		__snake_case     ,		__snake_case					)






					def   lowerCamelCase__   (			self  :      Any					)			->							str:
											__magic_name__,			__magic_name__:	Union[str, Any]							=       self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	with self.subTest(model_class.__name__					):
																							__magic_name__:	Any							=       self._prepare_for_class(__snake_case     ,		__snake_case					)
																							__magic_name__:	Any							=       model_class(__snake_case					)

																							@jax.jit
																							def model_jitted(__snake_case  :      List[str]     ,		**__snake_case  :      Optional[int]					):
																													return model(pixel_values=__snake_case     ,		**__snake_case					)

																							with self.subTest("""JIT Enabled"""					):
																													__magic_name__:	Dict							=       model_jitted(**__snake_case					).to_tuple()

																							with self.subTest("""JIT Disabled"""					):
																													with jax.disable_jit():
																																			__magic_name__:	Optional[int]							=       model_jitted(**__snake_case					).to_tuple()

																							self.assertEqual(len(__snake_case					)     ,		len(__snake_case					)					)
																							for jitted_output, output in zip(__snake_case     ,		__snake_case					):
																													self.assertEqual(jitted_output.shape     ,		output.shape					)



def   a    (     )    ->							Tuple:
						__magic_name__:	List[str]							=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
						return image



@require_flax
class       __A		(   unittest.TestCase			):

					@cached_property
					def   lowerCamelCase__   (			self  :      Tuple					)			->							Optional[int]:
											return AutoImageProcessor.from_pretrained("""facebook/regnet-y-040"""					) if is_vision_available() else None






					@slow
					def   lowerCamelCase__   (			self  :      Optional[Any]					)			->							List[Any]:
											__magic_name__:	List[Any]							=       FlaxRegNetForImageClassification.from_pretrained("""facebook/regnet-y-040"""					)

											__magic_name__:	List[Any]							=       self.default_image_processor
											__magic_name__:	Any							=       prepare_img()
											__magic_name__:	str							=       image_processor(images=__snake_case     ,		return_tensors="""np"""					)

											__magic_name__:	List[Any]							=       model(**__snake_case					)

											# verify the logits
											__magic_name__:	List[Any]							=       (1, 1_0_0_0)
											self.assertEqual(outputs.logits.shape     ,		__snake_case					)

											__magic_name__:	Union[str, Any]							=       jnp.array([-0.4180, -1.5051, -3.4836]					)

											self.assertTrue(jnp.allclose(outputs.logits[0, :3]     ,		__snake_case     ,		atol=1E-4					)					)











"""simple docstring"""





from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


__lowerCamelCase							=  logging.get_logger(__name__)



class       __A		(   SCREAMING_SNAKE_CASE_			):

					def   lowerCamelCase__   (			self  :      Optional[Any]     ,		__snake_case  :      Any					)			->							List[Any]:
											if isinstance(__snake_case     ,		__snake_case					):
																	__magic_name__:	Dict							=       [label.strip() for label in labels.split(""","""					) if label.strip()]
											return labels






					def __call__(			self  :      Optional[Any]     ,		__snake_case  :      str     ,		__snake_case  :      List[Any]     ,		__snake_case  :      List[Any]					)			->							int:
											if len(__snake_case					) == 0 or len(__snake_case					) == 0:
																	raise ValueError("""You must include at least one label and at least one sequence."""					)
											if hypothesis_template.format(labels[0]					) == hypothesis_template:
																	raise ValueError(
																	    (
																	        """The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. """
																	        """Make sure the passed template includes formatting syntax such as {{}} where the label should go."""
																	    ).format(__snake_case					)					)

											if isinstance(__snake_case     ,		__snake_case					):
																	__magic_name__:	Any							=       [sequences]

											__magic_name__:	List[Any]							=       []
											for sequence in sequences:
																	sequence_pairs.extend([[sequence, hypothesis_template.format(__snake_case					)] for label in labels]					)

											return sequence_pairs, sequences



@add_end_docstrings(SCREAMING_SNAKE_CASE_			)
class       __A		(   SCREAMING_SNAKE_CASE_			):

					def __init__(			self  :      Dict     ,		__snake_case  :      Dict=ZeroShotClassificationArgumentHandler()     ,		*__snake_case  :      Dict     ,		**__snake_case  :      Optional[int]					)			->							int:
											__magic_name__:	List[str]							=       args_parser
											super().__init__(*__snake_case     ,		**__snake_case					)
											if self.entailment_id == -1:
																	logger.warning(
																	    """Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to """
																	    """-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."""					)

					@property
					def   lowerCamelCase__   (			self  :      List[str]					)			->							str:
											for label, ind in self.model.config.labelaid.items():
																	if label.lower().startswith("""entail"""					):
																							return ind
											return -1

					def   lowerCamelCase__   (			self  :      Union[str, Any]     ,		__snake_case  :      Tuple     ,		__snake_case  :      List[Any]=True     ,		__snake_case  :      Tuple=True     ,		__snake_case  :      Tuple=TruncationStrategy.ONLY_FIRST     ,		**__snake_case  :      Union[str, Any]					)			->							int:
											__magic_name__:	Optional[int]							=       self.framework
											if self.tokenizer.pad_token is None:
																	# Override for tokenizers not supporting padding
																	logger.error(
																	    """Tokenizer was not supporting padding necessary for zero-shot, attempting to use """
																	    """ `pad_token=eos_token`"""					)
																	__magic_name__:	Tuple							=       self.tokenizer.eos_token
											try:
																	__magic_name__:	List[Any]							=       self.tokenizer(
																	    __snake_case     ,		add_special_tokens=__snake_case     ,		return_tensors=__snake_case     ,		padding=__snake_case     ,		truncation=__snake_case     ,		)
											except Exception as e:
																	if "too short" in str(__snake_case					):
																							# tokenizers might yell that we want to truncate
																							# to a value that is not even reached by the input.
																							# In that case we don't want to truncate.
																							# It seems there's not a really better way to catch that
																							# exception.

																							__magic_name__:	List[str]							=       self.tokenizer(
																							    __snake_case     ,		add_special_tokens=__snake_case     ,		return_tensors=__snake_case     ,		padding=__snake_case     ,		truncation=TruncationStrategy.DO_NOT_TRUNCATE     ,		)
																	else:
																							raise e

											return inputs

					def   lowerCamelCase__   (			self  :      Any     ,		**__snake_case  :      Optional[Any]					)			->							int:
											if kwargs.get("""multi_class"""     ,		__snake_case					) is not None:
																	__magic_name__:	List[str]							=       kwargs["""multi_class"""]
																	logger.warning(
																	    """The `multi_class` argument has been deprecated and renamed to `multi_label`. """
																	    """`multi_class` will be removed in a future version of Transformers."""					)
											__magic_name__:	Optional[Any]							=       {}
											if "candidate_labels" in kwargs:
																	__magic_name__:	str							=       self._args_parser._parse_labels(kwargs["""candidate_labels"""]					)
											if "hypothesis_template" in kwargs:
																	__magic_name__:	Optional[Any]							=       kwargs["""hypothesis_template"""]

											__magic_name__:	int							=       {}
											if "multi_label" in kwargs:
																	__magic_name__:	int							=       kwargs["""multi_label"""]
											return preprocess_params, {}, postprocess_params

					def __call__(			self  :      Any     ,		__snake_case  :      Union[str, List[str]]     ,		*__snake_case  :      Optional[int]     ,		**__snake_case  :      List[str]     ,		)			->							List[str]:
											if len(__snake_case					) == 0:
																	pass
											elif len(__snake_case					) == 1 and "candidate_labels" not in kwargs:
																	__magic_name__:	str							=       args[0]
											else:
																	raise ValueError(F'Unable to understand extra arguments {args}'					)

											return super().__call__(__snake_case     ,		**__snake_case					)

					def   lowerCamelCase__   (			self  :      Any     ,		__snake_case  :      int     ,		__snake_case  :      List[Any]=None     ,		__snake_case  :      Tuple="This example is {}."					)			->							List[Any]:
											__magic_name__,			__magic_name__:	int							=       self._args_parser(__snake_case     ,		__snake_case     ,		__snake_case					)

											for i, (candidate_label, sequence_pair) in enumerate(zip(__snake_case     ,		__snake_case					)					):
																	__magic_name__:	Dict							=       self._parse_and_tokenize([sequence_pair]					)

																	yield {
																	    "candidate_label": candidate_label,
																	    "sequence": sequences[0],
																	    "is_last": i == len(__snake_case					) - 1,
																	    **model_input,
																	}

					def   lowerCamelCase__   (			self  :      Dict     ,		__snake_case  :      int					)			->							Tuple:
											__magic_name__:	Optional[Any]							=       inputs["""candidate_label"""]
											__magic_name__:	List[str]							=       inputs["""sequence"""]
											__magic_name__:	Any							=       {k: inputs[k] for k in self.tokenizer.model_input_names}
											__magic_name__:	Optional[int]							=       self.model(**__snake_case					)

											__magic_name__:	Optional[Any]							=       {
											    """candidate_label""": candidate_label,
											    """sequence""": sequence,
											    """is_last""": inputs["""is_last"""],
											    **outputs,
											}
											return model_outputs






					def   lowerCamelCase__   (			self  :      Optional[int]     ,		__snake_case  :      str     ,		__snake_case  :      List[Any]=False					)			->							Any:
											__magic_name__:	List[Any]							=       [outputs["""candidate_label"""] for outputs in model_outputs]
											__magic_name__:	Any							=       [outputs["""sequence"""] for outputs in model_outputs]
											__magic_name__:	Tuple							=       np.concatenate([output["""logits"""].numpy() for output in model_outputs]					)
											__magic_name__:	Any							=       logits.shape[0]
											__magic_name__:	Any							=       len(__snake_case					)
											__magic_name__:	List[str]							=       N // n
											__magic_name__:	int							=       logits.reshape((num_sequences, n, -1)					)

											if multi_label or len(__snake_case					) == 1:
																	# softmax over the entailment vs. contradiction dim for each label independently
																	__magic_name__:	List[Any]							=       self.entailment_id
																	__magic_name__:	List[str]							=       -1 if entailment_id == 0 else 0
																	__magic_name__:	Tuple							=       reshaped_outputs[..., [contradiction_id, entailment_id]]
																	__magic_name__:	int							=       np.exp(__snake_case					) / np.exp(__snake_case					).sum(-1     ,		keepdims=__snake_case					)
																	__magic_name__:	List[str]							=       scores[..., 1]
											else:
																	# softmax the "entailment" logits over all candidate labels
																	__magic_name__:	List[str]							=       reshaped_outputs[..., self.entailment_id]
																	__magic_name__:	Tuple							=       np.exp(__snake_case					) / np.exp(__snake_case					).sum(-1     ,		keepdims=__snake_case					)

											__magic_name__:	Optional[Any]							=       list(reversed(scores[0].argsort()					)					)
											return {
											    "sequence": sequences[0],
											    "labels": [candidate_labels[i] for i in top_inds],
											    "scores": scores[0, top_inds].tolist(),
											}



