




'''simple docstring'''





import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
		from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor




class  _snake_case		:




			def __init__(					self				,							a__				,							a__=13				,							a__=32				,							a__=3				,							a__=4				,							a__=[10, 20, 30, 40]				,							a__=[2, 2, 3, 2]				,							a__=True				,							a__=True				,							a__=37				,							a__="gelu"				,							a__=10				,							a__=0.0_2				,							a__=["stage2", "stage3", "stage4"]				,							a__=[2, 3, 4]				,							a__=None				,							)				->				List[Any]:

										'''simple docstring'''




										snake_case_						=      parent
										snake_case_						=      batch_size
										snake_case_						=      image_size
										snake_case_						=      num_channels
										snake_case_						=      num_stages
										snake_case_						=      hidden_sizes
										snake_case_						=      depths
										snake_case_						=      is_training
										snake_case_						=      use_labels
										snake_case_						=      intermediate_size
										snake_case_						=      hidden_act
										snake_case_						=      num_labels
										snake_case_						=      initializer_range
										snake_case_						=      out_features
										snake_case_						=      out_indices
										snake_case_						=      scope




			def    lowerCAmelCase__				(					self							)				->				List[str]:

										'''simple docstring'''




										snake_case_						=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

										snake_case_						=      None
										if self.use_labels:
																	snake_case_						=      ids_tensor([self.batch_size]				,							self.num_labels							)

										snake_case_						=      self.get_config()
										return config, pixel_values, labels




			def    lowerCAmelCase__				(					self							)				->				Optional[int]:

										'''simple docstring'''




										return ConvNextConfig(
										    num_channels=self.num_channels				,							hidden_sizes=self.hidden_sizes				,							depths=self.depths				,							num_stages=self.num_stages				,							hidden_act=self.hidden_act				,							is_decoder=a__				,							initializer_range=self.initializer_range				,							out_features=self.out_features				,							out_indices=self.out_indices				,							num_labels=self.num_labels				,							)




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__							)				->				Tuple:

										'''simple docstring'''




										snake_case_						=      ConvNextModel(config=a__							)
										model.to(a__							)
										model.eval()
										snake_case_						=      model(a__							)
										# expected last hidden states: B, C, H // 32, W // 32
										self.parent.assertEqual(
										    result.last_hidden_state.shape				,							(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)				,							)




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__							)				->				List[str]:

										'''simple docstring'''




										snake_case_						=      ConvNextForImageClassification(a__							)
										model.to(a__							)
										model.eval()
										snake_case_						=      model(a__				,							labels=a__							)
										self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.num_labels)							)




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__							)				->				Optional[int]:

										'''simple docstring'''




										snake_case_						=      ConvNextBackbone(config=a__							)
										model.to(a__							)
										model.eval()
										snake_case_						=      model(a__							)

										# verify hidden states
										self.parent.assertEqual(len(result.feature_maps							)				,							len(config.out_features							)							)
										self.parent.assertListEqual(list(result.feature_maps[0].shape							)				,							[self.batch_size, self.hidden_sizes[1], 4, 4]							)

										# verify channels
										self.parent.assertEqual(len(model.channels							)				,							len(config.out_features							)							)
										self.parent.assertListEqual(model.channels				,							config.hidden_sizes[1:]							)

										# verify backbone works with out_features=None
										snake_case_						=      None
										snake_case_						=      ConvNextBackbone(config=a__							)
										model.to(a__							)
										model.eval()
										snake_case_						=      model(a__							)

										# verify feature maps
										self.parent.assertEqual(len(result.feature_maps							)				,							1							)
										self.parent.assertListEqual(list(result.feature_maps[0].shape							)				,							[self.batch_size, self.hidden_sizes[-1], 1, 1]							)

										# verify channels
										self.parent.assertEqual(len(model.channels							)				,							1							)
										self.parent.assertListEqual(model.channels				,							[config.hidden_sizes[-1]]							)




			def    lowerCAmelCase__				(					self							)				->				Optional[Any]:

										'''simple docstring'''




										snake_case_						=      self.prepare_config_and_inputs()
										snake_case_					,      snake_case_					,      snake_case_						=      config_and_inputs
										snake_case_						=      {"pixel_values": pixel_values}
										return config, inputs_dict




@require_torch
class  _snake_case		(	A__						,						A__						,						unittest.TestCase							):
			lowerCAmelCase_     :      Any						       =    (
			    (
			        ConvNextModel,
			        ConvNextForImageClassification,
			        ConvNextBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			lowerCAmelCase_     :      Optional[Any]						       =    (
			    {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
			    if is_torch_available()
			    else {}
			)

			lowerCAmelCase_     :      Any						       =    True
			lowerCAmelCase_     :      Union[str, Any]						       =    False
			lowerCAmelCase_     :      Any						       =    False
			lowerCAmelCase_     :      List[str]						       =    False
			lowerCAmelCase_     :      int						       =    False




			def    lowerCAmelCase__				(					self							)				->				Optional[Any]:

										'''simple docstring'''




										snake_case_						=      ConvNextModelTester(self							)
										snake_case_						=      ConfigTester(self				,							config_class=a__				,							has_text_modality=a__				,							hidden_size=37							)




			def    lowerCAmelCase__				(					self							)				->				Tuple:

										'''simple docstring'''




										self.create_and_test_config_common_properties()
										self.config_tester.create_and_test_config_to_json_string()
										self.config_tester.create_and_test_config_to_json_file()
										self.config_tester.create_and_test_config_from_and_save_pretrained()
										self.config_tester.create_and_test_config_with_num_labels()
										self.config_tester.check_config_can_be_init_without_params()
										self.config_tester.check_config_arguments_init()




			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




										return




			@unittest.skip(reason="ConvNext does not use inputs_embeds"							)
			def    lowerCAmelCase__				(					self							)				->				int:

										'''simple docstring'''




										pass




			@unittest.skip(reason="ConvNext does not support input and output embeddings"							)
			def    lowerCAmelCase__				(					self							)				->				Optional[int]:

										'''simple docstring'''




										pass




			@unittest.skip(reason="ConvNext does not use feedforward chunking"							)
			def    lowerCAmelCase__				(					self							)				->				List[str]:

										'''simple docstring'''




										pass




			def    lowerCAmelCase__				(					self							)				->				List[Any]:

										'''simple docstring'''




										snake_case_					,      snake_case_						=      self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	snake_case_						=      model_class(a__							)
																	snake_case_						=      inspect.signature(model.forward							)
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	snake_case_						=      [*signature.parameters.keys()]

																	snake_case_						=      ["pixel_values"]
																	self.assertListEqual(arg_names[:1]				,							a__							)




			def    lowerCAmelCase__				(					self							)				->				Tuple:

										'''simple docstring'''




										snake_case_						=      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*a__							)




			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




										snake_case_						=      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_backbone(*a__							)




			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




										def check_hidden_states_output(a__				,							a__				,							a__							):
																	snake_case_						=      model_class(a__							)
																	model.to(a__							)
																	model.eval()

																	with torch.no_grad():
																								snake_case_						=      model(**self._prepare_for_class(a__				,							a__							)							)

																	snake_case_						=      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																	snake_case_						=      self.model_tester.num_stages
																	self.assertEqual(len(a__							)				,							expected_num_stages + 1							)

																	# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
																	self.assertListEqual(
																	    list(hidden_states[0].shape[-2:]							)				,							[self.model_tester.image_size // 4, self.model_tester.image_size // 4]				,							)

										snake_case_					,      snake_case_						=      self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	snake_case_						=      True
																	check_hidden_states_output(a__				,							a__				,							a__							)

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	snake_case_						=      True

																	check_hidden_states_output(a__				,							a__				,							a__							)




			def    lowerCAmelCase__				(					self							)				->				List[str]:

										'''simple docstring'''




										snake_case_						=      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*a__							)




			@slow
			def    lowerCAmelCase__				(					self							)				->				Optional[Any]:

										'''simple docstring'''




										for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	snake_case_						=      ConvNextModel.from_pretrained(a__							)
																	self.assertIsNotNone(a__							)


def      UpperCamelCase_(	):

							'''simple docstring'''






							snake_case_						=      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
							return image




@require_torch
@require_vision
class  _snake_case		(	unittest.TestCase							):




			@cached_property
			def    lowerCAmelCase__				(					self							)				->				int:

										'''simple docstring'''




										return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224"							) if is_vision_available() else None




			@slow
			def    lowerCAmelCase__				(					self							)				->				int:

										'''simple docstring'''




										snake_case_						=      ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"							).to(a__							)

										snake_case_						=      self.default_image_processor
										snake_case_						=      prepare_img()
										snake_case_						=      image_processor(images=a__				,							return_tensors="pt"							).to(a__							)

										# forward pass
										with torch.no_grad():
																	snake_case_						=      model(**a__							)

										# verify the logits
										snake_case_						=      torch.Size((1, 1_000)							)
										self.assertEqual(outputs.logits.shape				,							a__							)

										snake_case_						=      torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]							).to(a__							)

										self.assertTrue(torch.allclose(outputs.logits[0, :3]				,							a__				,							atol=1e-4							)							)




@require_torch
class  _snake_case		(	unittest.TestCase						,						A__							):
			lowerCAmelCase_     :      str						       =    (ConvNextBackbone,) if is_torch_available() else ()
			lowerCAmelCase_     :      Tuple						       =    ConvNextConfig

			lowerCAmelCase_     :      Any						       =    False




			def    lowerCAmelCase__				(					self							)				->				int:

										'''simple docstring'''




										snake_case_						=      ConvNextModelTester(self							)












from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
							import tensorflow as tf

							from ..tf_utils import stable_softmax


if is_torch_available():
							import torch


A__	:			Dict			   = logging.get_logger(__name__)
@add_end_docstrings(
    A__		,r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """		,)
class       _UpperCAmelCase					(       A__	):

				"""simple docstring"""




				def 				lowercase__   (     self						:    Optional[int],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								if self.framework == "tf":
												lowercase__    =			tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()
								elif self.framework == "pt":
												lowercase__    =			torch.nonzero(input_ids == self.tokenizer.mask_token_id,  as_tuple=lowerCamelCase  )
								else:
												raise ValueError('''Unsupported framework'''  )
								return masked_index




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								lowercase__    =			self.get_masked_index(lowerCamelCase  )
								lowercase__    =			np.prod(masked_index.shape  )
								if numel < 1:
												raise PipelineException(
												    '''fill-mask''',  self.model.base_model_prefix,  F"""No mask_token ({self.tokenizer.mask_token}) found on the input""",  )




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  lowerCamelCase  ):
												for model_input in model_inputs:
																self._ensure_exactly_one_mask_token(model_input['''input_ids'''][0]  )
								else:
												for input_ids in model_inputs["input_ids"]:
																self._ensure_exactly_one_mask_token(lowerCamelCase  )




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    Union[str, Any],  lowerCamelCase						:    Optional[int]=None,  **lowerCamelCase						:    Dict  ):

								'''simple docstring'''
								if return_tensors is None:
												lowercase__    =			self.framework
								lowercase__    =			self.tokenizer(lowerCamelCase,  return_tensors=lowerCamelCase  )
								self.ensure_exactly_one_mask_token(lowerCamelCase  )
								return model_inputs




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    int  ):

								'''simple docstring'''
								lowercase__    =			self.model(**lowerCamelCase  )
								lowercase__    =			model_inputs['''input_ids''']
								return model_outputs




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    List[str],  lowerCamelCase						:    Tuple=5,  lowerCamelCase						:    List[Any]=None  ):

								'''simple docstring'''
								# Cap top_k if there are targets
								if target_ids is not None and target_ids.shape[0] < top_k:
												lowercase__    =			target_ids.shape[0]
								lowercase__    =			model_outputs['''input_ids'''][0]
								lowercase__    =			model_outputs['''logits''']

								if self.framework == "tf":
												lowercase__    =			tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()[:, 0]

												lowercase__    =			outputs.numpy()

												lowercase__    =			outputs[0, masked_index, :]
												lowercase__    =			stable_softmax(lowerCamelCase,  axis=-1  )
												if target_ids is not None:
																lowercase__    =			tf.gather_nd(tf.squeeze(lowerCamelCase,  0  ),  target_ids.reshape(-1,  1  )  )
																lowercase__    =			tf.expand_dims(lowerCamelCase,  0  )

												lowercase__    =			tf.math.top_k(lowerCamelCase,  k=lowerCamelCase  )
												lowercase__ ,						lowercase__    =			topk.values.numpy(), topk.indices.numpy()
								else:
												lowercase__    =			torch.nonzero(input_ids == self.tokenizer.mask_token_id,  as_tuple=lowerCamelCase  ).squeeze(-1  )
												# Fill mask pipeline supports only one ${mask_token} per sample

												lowercase__    =			outputs[0, masked_index, :]
												lowercase__    =			logits.softmax(dim=-1  )
												if target_ids is not None:
																lowercase__    =			probs[..., target_ids]

												lowercase__ ,						lowercase__    =			probs.topk(lowerCamelCase  )

								lowercase__    =			[]
								lowercase__    =			values.shape[0] == 1
								for i, (_values, _predictions) in enumerate(zip(values.tolist(),  predictions.tolist()  )  ):
												lowercase__    =			[]
												for v, p in zip(_values,  _predictions  ):
																# Copy is important since we're going to modify this array in place
																lowercase__    =			input_ids.numpy().copy()
																if target_ids is not None:
																				lowercase__    =			target_ids[p].tolist()

																lowercase__    =			p
																# Filter padding out:
																lowercase__    =			tokens[np.where(tokens != self.tokenizer.pad_token_id  )]
																# Originally we skip special tokens to give readable output.
																# For multi masks though, the other [MASK] would be removed otherwise
																# making the output look odd, so we add them back
																lowercase__    =			self.tokenizer.decode(lowerCamelCase,  skip_special_tokens=lowerCamelCase  )
																lowercase__    =			{'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]  ), '''sequence''': sequence}
																row.append(lowerCamelCase  )
												result.append(lowerCamelCase  )
								if single_mask:
												return result[0]
								return result




				def 				lowercase__   (     self						:    int,  lowerCamelCase						:    Optional[int],  lowerCamelCase						:    Dict=None  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  lowerCamelCase  ):
												lowercase__    =			[targets]
								try:
												lowercase__    =			self.tokenizer.get_vocab()
								except Exception:
												lowercase__    =			{}
								lowercase__    =			[]
								for target in targets:
												lowercase__    =			vocab.get(lowerCamelCase,  lowerCamelCase  )
												if id_ is None:
																lowercase__    =			self.tokenizer(
																    lowerCamelCase,  add_special_tokens=lowerCamelCase,  return_attention_mask=lowerCamelCase,  return_token_type_ids=lowerCamelCase,  max_length=1,  truncation=lowerCamelCase,  )['''input_ids''']
																if len(lowerCamelCase  ) == 0:
																				logger.warning(
																				    F"""The specified target token `{target}` does not exist in the model vocabulary. """
																				    '''We cannot replace it with anything meaningful, ignoring it'''  )
																				continue
																lowercase__    =			input_ids[0]
																# XXX: If users encounter this pass
																# it becomes pretty slow, so let's make sure
																# The warning enables them to fix the input to
																# get faster performance.
																logger.warning(
																    F"""The specified target token `{target}` does not exist in the model vocabulary. """
																    F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_  )}`."""  )
												target_ids.append(id_  )
								lowercase__    =			list(set(lowerCamelCase  )  )
								if len(lowerCamelCase  ) == 0:
												raise ValueError('''At least one target must be provided when passed.'''  )
								lowercase__    =			np.array(lowerCamelCase  )
								return target_ids




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    int=None,  lowerCamelCase						:    Any=None  ):

								'''simple docstring'''
								lowercase__    =			{}

								if targets is not None:
												lowercase__    =			self.get_target_ids(lowerCamelCase,  lowerCamelCase  )
												lowercase__    =			target_ids

								if top_k is not None:
												lowercase__    =			top_k

								if self.tokenizer.mask_token_id is None:
												raise PipelineException(
												    '''fill-mask''',  self.model.base_model_prefix,  '''The tokenizer does not define a `mask_token`.'''  )
								return {}, {}, postprocess_params




				def __call__(     self						:    List[Any],  lowerCamelCase						:    Optional[Any],  *lowerCamelCase						:    Optional[Any],  **lowerCamelCase						:    Optional[Any]  ):

								'''simple docstring'''
								lowercase__    =			super().__call__(lowerCamelCase,  **lowerCamelCase  )
								if isinstance(lowerCamelCase,  lowerCamelCase  ) and len(lowerCamelCase  ) == 1:
												return outputs[0]
								return outputs




