import copy
import inspect
import unittest

from transformers import PretrainedConfig, SwiftFormerConfig
from transformers.testing_utils import (
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
      import torch
      from torch import nn

      from transformers import SwiftFormerForImageClassification, SwiftFormerModel
      from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import ViTImageProcessor






class 		_lowerCamelCase		:
    def __init__(	self			,			lowerCAmelCase			,			lowerCAmelCase=13			,			lowerCAmelCase=3			,			lowerCAmelCase=True			,			lowerCAmelCase=True			,			lowerCAmelCase=0.1			,			lowerCAmelCase=0.1			,			lowerCAmelCase=224			,			lowerCAmelCase=1000			,			lowerCAmelCase=[3, 3, 6, 4]			,			lowerCAmelCase=[48, 56, 112, 220]			,			)							->       Dict:
     SCREAMING_SNAKE_CASE__: Any=   parent
     SCREAMING_SNAKE_CASE__: Dict=   batch_size
     SCREAMING_SNAKE_CASE__: Tuple=   num_channels
     SCREAMING_SNAKE_CASE__: Any=   is_training
     SCREAMING_SNAKE_CASE__: List[Any]=   use_labels
     SCREAMING_SNAKE_CASE__: str=   hidden_dropout_prob
     SCREAMING_SNAKE_CASE__: Any=   attention_probs_dropout_prob
     SCREAMING_SNAKE_CASE__: Dict=   num_labels
     SCREAMING_SNAKE_CASE__: Optional[int]=   image_size
     SCREAMING_SNAKE_CASE__: List[str]=   layer_depths
     SCREAMING_SNAKE_CASE__: int=   embed_dims
    def     UpperCamelCase_					(	self )							->       Optional[Any]:
     SCREAMING_SNAKE_CASE__: Optional[int]=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

     SCREAMING_SNAKE_CASE__: str=   None
     if self.use_labels:
      SCREAMING_SNAKE_CASE__: int=   ids_tensor([self.batch_size]			,			self.num_labels )

     SCREAMING_SNAKE_CASE__: int=   self.get_config()

     return config, pixel_values, labels
    def     UpperCamelCase_					(	self )							->       Tuple:
     return SwiftFormerConfig(
         depths=self.layer_depths			,			embed_dims=self.embed_dims			,			mlp_ratio=4			,			downsamples=[True, True, True, True]			,			hidden_act='''gelu'''			,			num_labels=self.num_labels			,			down_patch_size=3			,			down_stride=2			,			down_pad=1			,			drop_rate=0.0			,			drop_path_rate=0.0			,			use_layer_scale=lowerCAmelCase			,			layer_scale_init_value=1e-5			,			)
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Union[str, Any]:
     SCREAMING_SNAKE_CASE__: int=   SwiftFormerModel(config=lowerCAmelCase )
     model.to(lowerCAmelCase )
     model.eval()
     SCREAMING_SNAKE_CASE__: str=   model(lowerCAmelCase )
     self.parent.assertEqual(result.last_hidden_state.shape			,			(self.batch_size, self.embed_dims[-1], 7, 7) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Union[str, Any]:
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   self.num_labels
     SCREAMING_SNAKE_CASE__: Dict=   SwiftFormerForImageClassification(lowerCAmelCase )
     model.to(lowerCAmelCase )
     model.eval()
     SCREAMING_SNAKE_CASE__: Dict=   model(lowerCAmelCase			,			labels=lowerCAmelCase )
     self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels) )

     SCREAMING_SNAKE_CASE__: List[Any]=   SwiftFormerForImageClassification(lowerCAmelCase )
     model.to(lowerCAmelCase )
     model.eval()

     SCREAMING_SNAKE_CASE__: Dict=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
     SCREAMING_SNAKE_CASE__: List[str]=   model(lowerCAmelCase )
     self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels) )



    def     UpperCamelCase_					(	self )							->       int:
     ((SCREAMING_SNAKE_CASE__),						(SCREAMING_SNAKE_CASE__),						(SCREAMING_SNAKE_CASE__)): List[Any]=   self.prepare_config_and_inputs()
     SCREAMING_SNAKE_CASE__: Optional[int]=   {'''pixel_values''': pixel_values}
     return config, inputs_dict






@require_torch
class 		_lowerCamelCase		( UpperCamelCase_     ,  UpperCamelCase_     ,  unittest.TestCase     ):
    __a						=   (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
    __a						=   (
        {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification}
        if is_torch_available()
        else {}
    )

    __a						=   False
    __a						=   False
    __a						=   False
    __a						=   False
    __a						=   False
    def     UpperCamelCase_					(	self )							->       List[Any]:
     SCREAMING_SNAKE_CASE__: str=   SwiftFormerModelTester(self )
     SCREAMING_SNAKE_CASE__: Dict=   ConfigTester(
         self			,			config_class=lowerCAmelCase			,			has_text_modality=lowerCAmelCase			,			hidden_size=37			,			num_attention_heads=12			,			num_hidden_layers=12			,			)
    def     UpperCamelCase_					(	self )							->       Tuple:
     self.config_tester.run_common_tests()
    @unittest.skip(reason='''SwiftFormer does not use inputs_embeds''' )
    def     UpperCamelCase_					(	self )							->       Optional[Any]:
     pass
    def     UpperCamelCase_					(	self )							->       Any:
     SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: List[Any]=   self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
      SCREAMING_SNAKE_CASE__: Union[str, Any]=   model_class(lowerCAmelCase )
      SCREAMING_SNAKE_CASE__: Dict=   model.get_output_embeddings()
      self.assertTrue(x is None or isinstance(lowerCAmelCase			,			nn.Linear ) )
    def     UpperCamelCase_					(	self )							->       List[Any]:
     SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: Any=   self.model_tester.prepare_config_and_inputs_for_common()

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

      SCREAMING_SNAKE_CASE__: List[Any]=   ['''pixel_values''']
      self.assertListEqual(arg_names[:1]			,			lowerCAmelCase )
    def     UpperCamelCase_					(	self )							->       Dict:
     SCREAMING_SNAKE_CASE__: int=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase )
    def     UpperCamelCase_					(	self )							->       List[str]:
     SCREAMING_SNAKE_CASE__: List[Any]=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase )
    @slow
    def     UpperCamelCase_					(	self )							->       Any:
     for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      SCREAMING_SNAKE_CASE__: List[Any]=   SwiftFormerModel.from_pretrained(lowerCAmelCase )
      self.assertIsNotNone(lowerCAmelCase )
    @unittest.skip(reason='''SwiftFormer does not output attentions''' )
    def     UpperCamelCase_					(	self )							->       List[str]:
     pass
    def     UpperCamelCase_					(	self )							->       Tuple:
     def check_hidden_states_output(lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase ):
      SCREAMING_SNAKE_CASE__: Union[str, Any]=   model_class(lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()

      with torch.no_grad():
       SCREAMING_SNAKE_CASE__: Any=   model(**self._prepare_for_class(lowerCAmelCase			,			lowerCAmelCase ) )

      SCREAMING_SNAKE_CASE__: Union[str, Any]=   outputs.hidden_states

      SCREAMING_SNAKE_CASE__: str=   8
      self.assertEqual(len(lowerCAmelCase )			,			lowerCAmelCase )  # TODO

      # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
      # with the width and height being successively divided by 2, after every 2 blocks
      for i in range(len(lowerCAmelCase ) ):
       self.assertEqual(
           hidden_states[i].shape			,			torch.Size(
               [
                   self.model_tester.batch_size,
                   self.model_tester.embed_dims[i // 2],
                   (self.model_tester.image_size // 4) // 2 ** (i // 2),
                   (self.model_tester.image_size // 4) // 2 ** (i // 2),
               ] )			,			)

     SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: Optional[int]=   self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
      SCREAMING_SNAKE_CASE__: Optional[int]=   True
      check_hidden_states_output(lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )

      # check that output_hidden_states also work using config
      del inputs_dict["output_hidden_states"]
      SCREAMING_SNAKE_CASE__: Union[str, Any]=   True

      check_hidden_states_output(lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
    def     UpperCamelCase_					(	self )							->       List[str]:
     def _config_zero_init(lowerCAmelCase ):
      SCREAMING_SNAKE_CASE__: List[str]=   copy.deepcopy(lowerCAmelCase )
      for key in configs_no_init.__dict__.keys():
       if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
        setattr(lowerCAmelCase			,			lowerCAmelCase			,			1e-10 )
       if isinstance(getattr(lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )			,			lowerCAmelCase ):
        SCREAMING_SNAKE_CASE__: str=   _config_zero_init(getattr(lowerCAmelCase			,			lowerCAmelCase ) )
        setattr(lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
      return configs_no_init

     SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: Tuple=   self.model_tester.prepare_config_and_inputs_for_common()

     SCREAMING_SNAKE_CASE__: int=   _config_zero_init(lowerCAmelCase )
     for model_class in self.all_model_classes:
      SCREAMING_SNAKE_CASE__: List[str]=   model_class(config=lowerCAmelCase )
      for name, param in model.named_parameters():
       if param.requires_grad:
        self.assertIn(
            ((param.data.mean() * 1e9) / 1e9).round().item()			,			[0.0, 1.0]			,			msg=f'Parameter {name} of model {model_class} seems not properly initialized'			,			)



    @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
    def     UpperCamelCase_					(	self )							->       List[Any]:
     pass







def       A__   (						):
 SCREAMING_SNAKE_CASE__: List[Any]=   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
 return image






@require_torch
@require_vision
class 		_lowerCamelCase		( unittest.TestCase     ):
    @cached_property
    def     UpperCamelCase_					(	self )							->       Optional[int]:
     return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs''' ) if is_vision_available() else None



    @slow
    def     UpperCamelCase_					(	self )							->       str:
     SCREAMING_SNAKE_CASE__: Tuple=   SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs''' ).to(lowerCAmelCase )

     SCREAMING_SNAKE_CASE__: Optional[Any]=   self.default_image_processor
     SCREAMING_SNAKE_CASE__: Dict=   prepare_img()
     SCREAMING_SNAKE_CASE__: List[Any]=   image_processor(images=lowerCAmelCase			,			return_tensors='''pt''' ).to(lowerCAmelCase )

     # forward pass
     with torch.no_grad():
      SCREAMING_SNAKE_CASE__: int=   model(**lowerCAmelCase )

     # verify the logits
     SCREAMING_SNAKE_CASE__: int=   torch.Size((1, 1000) )
     self.assertEqual(outputs.logits.shape			,			lowerCAmelCase )

     SCREAMING_SNAKE_CASE__: List[Any]=   torch.tensor([[-2.1703e00, 2.1107e00, -2.0811e00]] ).to(lowerCAmelCase )
     self.assertTrue(torch.allclose(outputs.logits[0, :3]			,			lowerCAmelCase			,			atol=1e-4 ) )









'''simple docstring'''







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   __SCREAMING_SNAKE_CASE       (enum.Enum       ):


  """simple docstring"""


  _a  : Tuple      			=     0
  _a  : List[str]      			=     1
  _a  : int      			=     2





@add_end_docstrings(__A       )
class   __SCREAMING_SNAKE_CASE       (__A       ):


  """simple docstring"""


  _a  : str      			=     '''
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    '''







  def __init__(			self   ,	*UpperCamelCase__   ,	**UpperCamelCase__	):






         """simple docstring"""


         super().__init__(*UpperCamelCase__   ,	**UpperCamelCase__	)
         self.check_model_type(
             TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING	)
         if "prefix" not in self._preprocess_params:
                # This is very specific. The logic is quite complex and needs to be done
                # as a "default".
                # It also defines both some preprocess_kwargs and generate_kwargs
                # which is why we cannot put them in their respective methods.
                a_						     =			None
                if self.model.config.prefix is not None:
                       a_						     =			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_						     =			self.XL_PREFIX
                if prefix is not None:
                       # Recalculate some generate_kwargs linked to prefix.
                       a_     ,	a_     ,	a_						     =			self._sanitize_parameters(prefix=UpperCamelCase__   ,	**self._forward_params	)
                       a_						     =			{**self._preprocess_params, **preprocess_params}
                       a_						     =			{**self._forward_params, **forward_params}







  def    _a       (			self   ,	UpperCamelCase__=None   ,	UpperCamelCase__=None   ,	UpperCamelCase__=None   ,	UpperCamelCase__=None   ,	UpperCamelCase__=None   ,	UpperCamelCase__=None   ,	UpperCamelCase__=None   ,	UpperCamelCase__=None   ,	**UpperCamelCase__   ,	):






         """simple docstring"""


         a_						     =			{}
         if prefix is not None:
                a_						     =			prefix
         if prefix:
                a_						     =			self.tokenizer(
                    UpperCamelCase__   ,	padding=UpperCamelCase__   ,	add_special_tokens=UpperCamelCase__   ,	return_tensors=self.framework	)
                a_						     =			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_						     =			handle_long_generation

         preprocess_params.update(UpperCamelCase__	)
         a_						     =			generate_kwargs

         a_						     =			{}
         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_						     =			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_						     =			ReturnType.TENSORS
         if return_type is not None:
                a_						     =			return_type
         if clean_up_tokenization_spaces is not None:
                a_						     =			clean_up_tokenization_spaces

         if stop_sequence is not None:
                a_						     =			self.tokenizer.encode(UpperCamelCase__   ,	add_special_tokens=UpperCamelCase__	)
                if len(UpperCamelCase__	) > 1:
                       warnings.warn(
                           'Stopping on a multiple token sequence is not yet supported on transformers. The first token of'
                           ' the stop sequence will be used as the stop sequence string in the interim.'	)
                a_						     =			stop_sequence_ids[0]

         return preprocess_params, forward_params, postprocess_params







  def    _a       (			self   ,	*UpperCamelCase__   ,	**UpperCamelCase__	):






         """simple docstring"""


         if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
                kwargs.update({'add_space_before_punct_symbol': True}	)

         return super()._parse_and_tokenize(*UpperCamelCase__   ,	**UpperCamelCase__	)







  def __call__(			self   ,	UpperCamelCase__   ,	**UpperCamelCase__	):






         """simple docstring"""


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







  def    _a       (			self   ,	UpperCamelCase__   ,	UpperCamelCase__=""   ,	UpperCamelCase__=None   ,	**UpperCamelCase__	):






         """simple docstring"""


         a_						     =			self.tokenizer(
             prefix + prompt_text   ,	padding=UpperCamelCase__   ,	add_special_tokens=UpperCamelCase__   ,	return_tensors=self.framework	)
         a_						     =			prompt_text

         if handle_long_generation == "hole":
                a_						     =			inputs['input_ids'].shape[-1]
                if "max_new_tokens" in generate_kwargs:
                       a_						     =			generate_kwargs['max_new_tokens']
                else:
                       a_						     =			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_						     =			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_						     =			inputs['input_ids'][:, -keep_length:]
                       if "attention_mask" in inputs:
                              a_						     =			inputs['attention_mask'][:, -keep_length:]

         return inputs







  def    _a       (			self   ,	UpperCamelCase__   ,	**UpperCamelCase__	):






         """simple docstring"""


         a_						     =			model_inputs['input_ids']
         a_						     =			model_inputs.get('attention_mask'   ,	UpperCamelCase__	)
         # Allow empty prompts
         if input_ids.shape[1] == 0:
                a_						     =			None
                a_						     =			None
                a_						     =			1
         else:
                a_						     =			input_ids.shape[0]
         a_						     =			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_						     =			generate_kwargs.pop('prefix_length'   ,	0	)
         if prefix_length > 0:
                a_						     =			'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_						     =			generate_kwargs.get('max_length'	) or self.model.config.max_length
                       generate_kwargs["max_length"] += prefix_length
                a_						     =			'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_						     =			self.model.generate(input_ids=UpperCamelCase__   ,	attention_mask=UpperCamelCase__   ,	**UpperCamelCase__	)
         a_						     =			generated_sequence.shape[0]
         if self.framework == "pt":
                a_						     =			generated_sequence.reshape(UpperCamelCase__   ,	out_b // in_b   ,	*generated_sequence.shape[1:]	)
         elif self.framework == "tf":
                a_						     =			tf.reshape(UpperCamelCase__   ,	(in_b, out_b // in_b, *generated_sequence.shape[1:])	)
         return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}







  def    _a       (			self   ,	UpperCamelCase__   ,	UpperCamelCase__=ReturnType.FULL_TEXT   ,	UpperCamelCase__=True	):






         """simple docstring"""


         a_						     =			model_outputs['generated_sequence'][0]
         a_						     =			model_outputs['input_ids']
         a_						     =			model_outputs['prompt_text']
         a_						     =			generated_sequence.numpy().tolist()
         a_						     =			[]
         for sequence in generated_sequence:
                if return_type == ReturnType.TENSORS:
                       a_						     =			{'generated_token_ids': sequence}
                elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
                       # Decode text
                       a_						     =			self.tokenizer.decode(
                           UpperCamelCase__   ,	skip_special_tokens=UpperCamelCase__   ,	clean_up_tokenization_spaces=UpperCamelCase__   ,	)

                       # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
                       if input_ids is None:
                              a_						     =			0
                       else:
                              a_						     =			len(
                                  self.tokenizer.decode(
                                      input_ids[0]   ,	skip_special_tokens=UpperCamelCase__   ,	clean_up_tokenization_spaces=UpperCamelCase__   ,	)	)

                       if return_type == ReturnType.FULL_TEXT:
                              a_						     =			prompt_text + text[prompt_length:]
                       else:
                              a_						     =			text[prompt_length:]

                       a_						     =			{'generated_text': all_text}
                records.append(UpperCamelCase__	)

         return records




