



"""simple docstring"""

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  _UpperCAmelCase :

 def __init__(  self	: Tuple						,  lowercase_	: Optional[int]						,  lowercase_	: List[str]=13						,  lowercase_	: Optional[int]=3						,  lowercase_	: str=True						,  lowercase_	: int=True						,  lowercase_	: Union[str, Any]=0.1						,  lowercase_	: Union[str, Any]=0.1						,  lowercase_	: Any=224						,  lowercase_	: int=1000						,  lowercase_	: Optional[Any]=[3, 3, 6, 4]						,  lowercase_	: Any=[48, 56, 112, 220]						,  ):
     snake_case_				:  Optional[Any]       =			parent
     snake_case_				:  Optional[int]       =			batch_size
     snake_case_				:  List[Any]       =			num_channels
     snake_case_				:  List[Any]       =			is_training
     snake_case_				:  Union[str, Any]       =			use_labels
     snake_case_				:  Optional[Any]       =			hidden_dropout_prob
     snake_case_				:  int       =			attention_probs_dropout_prob
     snake_case_				:  List[Any]       =			num_labels
     snake_case_				:  Any       =			image_size
     snake_case_				:  Union[str, Any]       =			layer_depths
     snake_case_				:  List[str]       =			embed_dims

 def 		_snake_case      (  self	: int       ):
     snake_case_				:  Any       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

     snake_case_				:  Dict       =			self.get_config()

     return config, pixel_values, labels

 def 		_snake_case      (  self	: Any       ):
     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=lowercase_						,  layer_scale_init_value=1E-5						,  )

 def 		_snake_case      (  self	: Union[str, Any]						,  lowercase_	: Tuple						,  lowercase_	: str						,  lowercase_	: Any       ):
     snake_case_				:  Tuple       =			SwiftFormerModel(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  Dict       =			model(lowercase_       )
     self.parent.assertEqual(result.last_hidden_state.shape						,  (self.batch_size, self.embed_dims[-1], 7, 7)       )

 def 		_snake_case      (  self	: Any						,  lowercase_	: List[Any]						,  lowercase_	: Dict						,  lowercase_	: List[str]       ):
     snake_case_				:  Union[str, Any]       =			self.num_labels
     snake_case_				:  Any       =			SwiftFormerForImageClassification(lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  int       =			model(lowercase_						,  labels=lowercase_       )
     self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.num_labels)       )

     snake_case_				:  Tuple       =			SwiftFormerForImageClassification(lowercase_       )
     model.to(lowercase_       )
     model.eval()

     snake_case_				:  Union[str, Any]       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )
     snake_case_				:  Dict       =			model(lowercase_       )
     self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.num_labels)       )






 def 		_snake_case      (  self	: int       ):
     ((snake_case_),			(snake_case_),			(snake_case_))				:  Tuple       =			self.prepare_config_and_inputs()
     snake_case_				:  Tuple       =			{'''pixel_values''': pixel_values}
     return config, inputs_dict





@require_torch
class  _UpperCAmelCase (    lowerCAmelCase__					,  lowerCAmelCase__					,  unittest.TestCase):
 _lowerCAmelCase     :    Optional[Any]	      =	(SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
 _lowerCAmelCase     :    Dict	      =	(
     {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification}
     if is_torch_available()
     else {}
 )

 _lowerCAmelCase     :    List[Any]	      =	False
 _lowerCAmelCase     :    List[str]	      =	False
 _lowerCAmelCase     :    Union[str, Any]	      =	False
 _lowerCAmelCase     :    Union[str, Any]	      =	False
 _lowerCAmelCase     :    List[Any]	      =	False

 def 		_snake_case      (  self	: List[str]       ):
     snake_case_				:  Optional[int]       =			SwiftFormerModelTester(self       )
     snake_case_				:  Optional[Any]       =			ConfigTester(
         self						,  config_class=lowercase_						,  has_text_modality=lowercase_						,  hidden_size=37						,  num_attention_heads=12						,  num_hidden_layers=12						,  )

 def 		_snake_case      (  self	: Optional[int]       ):
     self.config_tester.run_common_tests()

 @unittest.skip(reason='''SwiftFormer does not use inputs_embeds'''       )
 def 		_snake_case      (  self	: Union[str, Any]       ):
     pass

 def 		_snake_case      (  self	: List[str]       ):
     snake_case_,			snake_case_				:  Optional[Any]       =			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         snake_case_				:  List[str]       =			model_class(lowercase_       )
         snake_case_				:  Any       =			model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(lowercase_						,  nn.Linear       )       )

 def 		_snake_case      (  self	: int       ):
     snake_case_,			snake_case_				:  Tuple       =			self.model_tester.prepare_config_and_inputs_for_common()

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

         snake_case_				:  Optional[Any]       =			['''pixel_values''']
         self.assertListEqual(arg_names[:1]						,  lowercase_       )

 def 		_snake_case      (  self	: List[str]       ):
     snake_case_				:  Union[str, Any]       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_       )

 def 		_snake_case      (  self	: List[str]       ):
     snake_case_				:  List[Any]       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowercase_       )

 @slow
 def 		_snake_case      (  self	: str       ):
     for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case_				:  int       =			SwiftFormerModel.from_pretrained(lowercase_       )
         self.assertIsNotNone(lowercase_       )

 @unittest.skip(reason='''SwiftFormer does not output attentions'''       )
 def 		_snake_case      (  self	: str       ):
     pass

 def 		_snake_case      (  self	: Tuple       ):
     def check_hidden_states_output(lowercase_	: Tuple						,  lowercase_	: Optional[Any]						,  lowercase_	: Union[str, Any]       ):
         snake_case_				:  int       =			model_class(lowercase_       )
         model.to(lowercase_       )
         model.eval()

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

         snake_case_				:  List[str]       =			outputs.hidden_states

         snake_case_				:  str       =			8
         self.assertEqual(len(lowercase_       )						,  lowercase_       )  # 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(lowercase_       )       ):
             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),
                     ]       )						,  )

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

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

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

         check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_       )

 def 		_snake_case      (  self	: List[Any]       ):
     def _config_zero_init(lowercase_	: List[Any]       ):
         snake_case_				:  Optional[int]       =			copy.deepcopy(lowercase_       )
         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(lowercase_						,  lowercase_						,  1E-10       )
             if isinstance(getattr(lowercase_						,  lowercase_						,  lowercase_       )						,  lowercase_       ):
                 snake_case_				:  Optional[int]       =			_config_zero_init(getattr(lowercase_						,  lowercase_       )       )
                 setattr(lowercase_						,  lowercase_						,  lowercase_       )
         return configs_no_init

     snake_case_,			snake_case_				:  Dict       =			self.model_tester.prepare_config_and_inputs_for_common()

     snake_case_				:  int       =			_config_zero_init(lowercase_       )
     for model_class in self.all_model_classes:
         snake_case_				:  Union[str, Any]       =			model_class(config=lowercase_       )
         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 		_snake_case      (  self	: Any       ):
     pass





def __lowercase    (							):
    snake_case_				:  Optional[int]       =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
    return image






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

 @cached_property
 def 		_snake_case      (  self	: List[str]       ):
     return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs'''       ) if is_vision_available() else None






 @slow
 def 		_snake_case      (  self	: Optional[Any]       ):
     snake_case_				:  int       =			SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs'''       ).to(lowercase_       )

     snake_case_				:  str       =			self.default_image_processor
     snake_case_				:  Union[str, Any]       =			prepare_img()
     snake_case_				:  Tuple       =			image_processor(images=lowercase_						,  return_tensors='''pt'''       ).to(lowercase_       )

     # forward pass
     with torch.no_grad():
         snake_case_				:  List[Any]       =			model(**lowercase_       )

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

     snake_case_				:  Optional[int]       =			torch.tensor([[-2.1703E00, 2.1107E00, -2.0811E00]]       ).to(lowercase_       )
     self.assertTrue(torch.allclose(outputs.logits[0, :3]						,  lowercase_						,  atol=1E-4       )       )










"""simple docstring"""

import tensorflow as tf

from ...tf_utils import shape_list




class  _UpperCAmelCase (    tf.keras.layers.Layer):

 def __init__(  self	: int						,  lowercase_	: Tuple						,  lowercase_	: Union[str, Any]						,  lowercase_	: Tuple						,  lowercase_	: List[Any]						,  lowercase_	: Tuple=1						,  lowercase_	: List[str]=False						,  **lowercase_	: Optional[Any]       ):
     super().__init__(**lowercase_       )

     snake_case_				:  int       =			vocab_size
     snake_case_				:  Union[str, Any]       =			d_embed
     snake_case_				:  Optional[int]       =			d_proj

     snake_case_				:  int       =			cutoffs + [vocab_size]
     snake_case_				:  Optional[int]       =			[0] + self.cutoffs
     snake_case_				:  List[str]       =			div_val

     snake_case_				:  int       =			self.cutoffs[0]
     snake_case_				:  Optional[Any]       =			len(self.cutoffs       ) - 1
     snake_case_				:  Any       =			self.shortlist_size + self.n_clusters
     snake_case_				:  Dict       =			keep_order

     snake_case_				:  Tuple       =			[]
     snake_case_				:  Optional[Any]       =			[]

 def 		_snake_case      (  self	: Dict						,  lowercase_	: int       ):
     if self.n_clusters > 0:
         snake_case_				:  Tuple       =			self.add_weight(
             shape=(self.n_clusters, self.d_embed)						,  initializer='''zeros'''						,  trainable=lowercase_						,  name='''cluster_weight'''       )
         snake_case_				:  List[str]       =			self.add_weight(
             shape=(self.n_clusters,)						,  initializer='''zeros'''						,  trainable=lowercase_						,  name='''cluster_bias'''       )

     if self.div_val == 1:
         for i in range(len(self.cutoffs       )       ):
             if self.d_proj != self.d_embed:
                 snake_case_				:  List[Any]       =			self.add_weight(
                     shape=(self.d_embed, self.d_proj)						,  initializer='''zeros'''						,  trainable=lowercase_						,  name=f"out_projs_._{i}"						,  )
                 self.out_projs.append(lowercase_       )
             else:
                 self.out_projs.append(lowercase_       )
             snake_case_				:  Any       =			self.add_weight(
                 shape=(self.vocab_size, self.d_embed)						,  initializer='''zeros'''						,  trainable=lowercase_						,  name=f"out_layers_._{i}_._weight"						,  )
             snake_case_				:  Any       =			self.add_weight(
                 shape=(self.vocab_size,)						,  initializer='''zeros'''						,  trainable=lowercase_						,  name=f"out_layers_._{i}_._bias"						,  )
             self.out_layers.append((weight, bias)       )
     else:
         for i in range(len(self.cutoffs       )       ):
             snake_case_,			snake_case_				:  str       =			self.cutoff_ends[i], self.cutoff_ends[i + 1]
             snake_case_				:  List[str]       =			self.d_embed // (self.div_val**i)

             snake_case_				:  Optional[Any]       =			self.add_weight(
                 shape=(d_emb_i, self.d_proj)						,  initializer='''zeros'''						,  trainable=lowercase_						,  name=f"out_projs_._{i}"       )
             self.out_projs.append(lowercase_       )
             snake_case_				:  Any       =			self.add_weight(
                 shape=(r_idx - l_idx, d_emb_i)						,  initializer='''zeros'''						,  trainable=lowercase_						,  name=f"out_layers_._{i}_._weight"						,  )
             snake_case_				:  List[Any]       =			self.add_weight(
                 shape=(r_idx - l_idx,)						,  initializer='''zeros'''						,  trainable=lowercase_						,  name=f"out_layers_._{i}_._bias"						,  )
             self.out_layers.append((weight, bias)       )
     super().build(lowercase_       )

 @staticmethod
 def 		_snake_case      (  lowercase_	: Dict						,  lowercase_	: Union[str, Any]						,  lowercase_	: Optional[int]						,  lowercase_	: str=None       ):
     snake_case_				:  str       =			x
     if proj is not None:
         snake_case_				:  str       =			tf.einsum('''ibd,ed->ibe'''						,  lowercase_						,  lowercase_       )
     return tf.einsum('''ibd,nd->ibn'''						,  lowercase_						,  lowercase_       ) + b

 @staticmethod
 def 		_snake_case      (  lowercase_	: Tuple						,  lowercase_	: Union[str, Any]       ):
     snake_case_				:  Optional[int]       =			shape_list(lowercase_       )
     snake_case_				:  Any       =			tf.range(lp_size[0]						,  dtype=target.dtype       )
     snake_case_				:  Optional[int]       =			tf.stack([r, target]						,  1       )
     return tf.gather_nd(lowercase_						,  lowercase_       )






 def 		_snake_case      (  self	: Tuple						,  lowercase_	: Union[str, Any]						,  lowercase_	: int						,  lowercase_	: Tuple=True						,  lowercase_	: Tuple=False       ):
     snake_case_				:  Optional[int]       =			0
     if self.n_clusters == 0:
         snake_case_				:  List[str]       =			self._logit(lowercase_						,  self.out_layers[0][0]						,  self.out_layers[0][1]						,  self.out_projs[0]       )
         if target is not None:
             snake_case_				:  List[Any]       =			tf.nn.sparse_softmax_cross_entropy_with_logits(labels=lowercase_						,  logits=lowercase_       )
         snake_case_				:  List[Any]       =			tf.nn.log_softmax(lowercase_						,  axis=-1       )
     else:
         snake_case_				:  Optional[int]       =			shape_list(lowercase_       )
         snake_case_				:  Any       =			[]
         snake_case_				:  List[str]       =			tf.zeros(hidden_sizes[:2]       )
         for i in range(len(self.cutoffs       )       ):
             snake_case_,			snake_case_				:  Union[str, Any]       =			self.cutoff_ends[i], self.cutoff_ends[i + 1]
             if target is not None:
                 snake_case_				:  Optional[Any]       =			(target >= l_idx) & (target < r_idx)
                 snake_case_				:  Any       =			tf.where(lowercase_       )
                 snake_case_				:  List[Any]       =			tf.boolean_mask(lowercase_						,  lowercase_       ) - l_idx

             if self.div_val == 1:
                 snake_case_				:  Optional[int]       =			self.out_layers[0][0][l_idx:r_idx]
                 snake_case_				:  List[Any]       =			self.out_layers[0][1][l_idx:r_idx]
             else:
                 snake_case_				:  Dict       =			self.out_layers[i][0]
                 snake_case_				:  str       =			self.out_layers[i][1]

             if i == 0:
                 snake_case_				:  Tuple       =			tf.concat([cur_W, self.cluster_weight]						,  0       )
                 snake_case_				:  List[str]       =			tf.concat([cur_b, self.cluster_bias]						,  0       )

                 snake_case_				:  List[Any]       =			self._logit(lowercase_						,  lowercase_						,  lowercase_						,  self.out_projs[0]       )
                 snake_case_				:  Union[str, Any]       =			tf.nn.log_softmax(lowercase_       )
                 out.append(head_logprob[..., : self.cutoffs[0]]       )
                 if target is not None:
                     snake_case_				:  int       =			tf.boolean_mask(lowercase_						,  lowercase_       )
                     snake_case_				:  str       =			self._gather_logprob(lowercase_						,  lowercase_       )
             else:
                 snake_case_				:  Union[str, Any]       =			self._logit(lowercase_						,  lowercase_						,  lowercase_						,  self.out_projs[i]       )
                 snake_case_				:  List[str]       =			tf.nn.log_softmax(lowercase_       )
                 snake_case_				:  Dict       =			self.cutoffs[0] + i - 1  # No probability for the head cluster
                 snake_case_				:  Union[str, Any]       =			head_logprob[..., cluster_prob_idx, None] + tail_logprob
                 out.append(lowercase_       )
                 if target is not None:
                     snake_case_				:  Optional[int]       =			tf.boolean_mask(lowercase_						,  lowercase_       )
                     snake_case_				:  Dict       =			tf.boolean_mask(lowercase_						,  lowercase_       )
                     snake_case_				:  Union[str, Any]       =			self._gather_logprob(lowercase_						,  lowercase_       )
                     cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
             if target is not None:
                 loss += tf.scatter_nd(lowercase_						,  -cur_logprob						,  shape_list(lowercase_       )       )
         snake_case_				:  Union[str, Any]       =			tf.concat(lowercase_						,  axis=-1       )

     if target is not None:
         if return_mean:
             snake_case_				:  Dict       =			tf.reduce_mean(lowercase_       )
         # Add the training-time loss value to the layer using `self.add_loss()`.
         self.add_loss(lowercase_       )

         # Log the loss as a metric (we could log arbitrary metrics,
         # including different metrics for training and inference.
         self.add_metric(lowercase_						,  name=self.name						,  aggregation='''mean''' if return_mean else ''''''       )

     return out





