



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						,					__UpperCAmelCase						,					__UpperCAmelCase=13						,					__UpperCAmelCase=3						,					__UpperCAmelCase=True						,					__UpperCAmelCase=True						,					__UpperCAmelCase=0.1						,					__UpperCAmelCase=0.1						,					__UpperCAmelCase=224						,					__UpperCAmelCase=1000						,					__UpperCAmelCase=[3, 3, 6, 4]						,					__UpperCAmelCase=[48, 56, 112, 220]						,					):



    '''simple docstring'''
    __lowerCamelCase    				=     parent
    __lowerCamelCase    				=     batch_size
    __lowerCamelCase    				=     num_channels
    __lowerCamelCase    				=     is_training
    __lowerCamelCase    				=     use_labels
    __lowerCamelCase    				=     hidden_dropout_prob
    __lowerCamelCase    				=     attention_probs_dropout_prob
    __lowerCamelCase    				=     num_labels
    __lowerCamelCase    				=     image_size
    __lowerCamelCase    				=     layer_depths
    __lowerCamelCase    				=     embed_dims




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

    __lowerCamelCase    				=     self.get_config()

    return config, pixel_values, labels




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    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=__UpperCAmelCase						,					layer_scale_init_value=1E-5						,					)




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     SwiftFormerModel(config=__UpperCAmelCase					)
    model.to(__UpperCAmelCase					)
    model.eval()
    __lowerCamelCase    				=     model(__UpperCAmelCase					)
    self.parent.assertEqual(result.last_hidden_state.shape						,					(self.batch_size, self.embed_dims[-1], 7, 7)					)




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.num_labels
    __lowerCamelCase    				=     SwiftFormerForImageClassification(__UpperCAmelCase					)
    model.to(__UpperCAmelCase					)
    model.eval()
    __lowerCamelCase    				=     model(__UpperCAmelCase						,					labels=__UpperCAmelCase					)
    self.parent.assertEqual(result.logits.shape						,					(self.batch_size, self.num_labels)					)

    __lowerCamelCase    				=     SwiftFormerForImageClassification(__UpperCAmelCase					)
    model.to(__UpperCAmelCase					)
    model.eval()

    __lowerCamelCase    				=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)
    __lowerCamelCase    				=     model(__UpperCAmelCase					)
    self.parent.assertEqual(result.logits.shape						,					(self.batch_size, self.num_labels)					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    ((__lowerCamelCase)				,(__lowerCamelCase)				,(__lowerCamelCase))    				=     self.prepare_config_and_inputs()
    __lowerCamelCase    				=     {'''pixel_values''': pixel_values}
    return config, inputs_dict



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

 lowerCAmelCase__							       =	False
 lowerCAmelCase__							       =	False
 lowerCAmelCase__							       =	False
 lowerCAmelCase__							       =	False
 lowerCAmelCase__							       =	False




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     SwiftFormerModelTester(self					)
    __lowerCamelCase    				=     ConfigTester(
        self						,					config_class=__UpperCAmelCase						,					has_text_modality=__UpperCAmelCase						,					hidden_size=37						,					num_attention_heads=12						,					num_hidden_layers=12						,					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    self.config_tester.run_common_tests()




 @unittest.skip(reason='''SwiftFormer does not use inputs_embeds'''					)
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    pass




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       __lowerCamelCase    				=     model_class(__UpperCAmelCase					)
       __lowerCamelCase    				=     model.get_output_embeddings()
       self.assertTrue(x is None or isinstance(__UpperCAmelCase						,					nn.Linear					)					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()

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

       __lowerCamelCase    				=     ['''pixel_values''']
       self.assertListEqual(arg_names[:1]						,					__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase					)




 @slow
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       __lowerCamelCase    				=     SwiftFormerModel.from_pretrained(__UpperCAmelCase					)
       self.assertIsNotNone(__UpperCAmelCase					)




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



    '''simple docstring'''
    pass




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    def check_hidden_states_output(__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					):
       __lowerCamelCase    				=     model_class(__UpperCAmelCase					)
       model.to(__UpperCAmelCase					)
       model.eval()

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

       __lowerCamelCase    				=     outputs.hidden_states

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

    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       __lowerCamelCase    				=     True
       check_hidden_states_output(__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					)

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

       check_hidden_states_output(__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    def _config_zero_init(__UpperCAmelCase					):
       __lowerCamelCase    				=     copy.deepcopy(__UpperCAmelCase					)
       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(__UpperCAmelCase						,					__UpperCAmelCase						,					1E-1_0					)
          if isinstance(getattr(__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					)						,					__UpperCAmelCase					):
             __lowerCamelCase    				=     _config_zero_init(getattr(__UpperCAmelCase						,					__UpperCAmelCase					)					)
             setattr(__UpperCAmelCase						,					__UpperCAmelCase						,					__UpperCAmelCase					)
       return configs_no_init

    __lowerCamelCase				,__lowerCamelCase    				=     self.model_tester.prepare_config_and_inputs_for_common()

    __lowerCamelCase    				=     _config_zero_init(__UpperCAmelCase					)
    for model_class in self.all_model_classes:
       __lowerCamelCase    				=     model_class(config=__UpperCAmelCase					)
       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 							lowerCamelCase   (    self					):



    '''simple docstring'''
    pass





def 		a__      (		):
   __lowerCamelCase    				=     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
   return image





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




 @cached_property
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs'''					) if is_vision_available() else None




 @slow
 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs'''					).to(__UpperCAmelCase					)

    __lowerCamelCase    				=     self.default_image_processor
    __lowerCamelCase    				=     prepare_img()
    __lowerCamelCase    				=     image_processor(images=__UpperCAmelCase						,					return_tensors='''pt'''					).to(__UpperCAmelCase					)

    # forward pass
    with torch.no_grad():
       __lowerCamelCase    				=     model(**__UpperCAmelCase					)

    # verify the logits
    __lowerCamelCase    				=     torch.Size((1, 1000)					)
    self.assertEqual(outputs.logits.shape						,					__UpperCAmelCase					)

    __lowerCamelCase    				=     torch.tensor([[-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0]]					).to(__UpperCAmelCase					)
    self.assertTrue(torch.allclose(outputs.logits[0, :3]						,					__UpperCAmelCase						,					atol=1E-4					)					)











def 		a__      (		_UpperCamelCase      :			list[int]				):
   if not numbers:
      return 0

   if not isinstance(_UpperCamelCase			,(list, tuple)				) or not all(
       isinstance(_UpperCamelCase			,_UpperCamelCase				) for number in numbers				):
      raise ValueError('''numbers must be an iterable of integers'''				)

   __lowerCamelCase    				=     __lowerCamelCase    				=     __lowerCamelCase    				=     numbers[0]

   for i in range(1			,len(_UpperCamelCase				)				):
      # update the maximum and minimum subarray products
      __lowerCamelCase    				=     numbers[i]
      if number < 0:
         __lowerCamelCase				,__lowerCamelCase    				=     min_till_now, max_till_now
      __lowerCamelCase    				=     max(_UpperCamelCase			,max_till_now * number				)
      __lowerCamelCase    				=     min(_UpperCamelCase			,min_till_now * number				)

      # update the maximum product found till now
      __lowerCamelCase    				=     max(_UpperCamelCase			,_UpperCamelCase				)

   return max_prod






