

import random





def 	__a     (      A__			:  int			,  A__			:  float			,  A__			:  bool = False       ):
    SCREAMING_SNAKE_CASE										=   {i: [] for i in range(A__       )}

    # if probability is greater or equal than 1, then generate a complete graph
    if probability >= 1:
        return complete_graph(A__       )
    # if probability is lower or equal than 0, then return a graph without edges
    if probability <= 0:
        return graph

    # for each couple of nodes, add an edge from u to v
    # if the number randomly generated is greater than probability probability
    for i in range(A__       ):
        for j in range(i + 1			,  A__       ):
            if random.random() < probability:
                graph[i].append(A__       )
                if not directed:
                    # if the graph is undirected, add an edge in from j to i, either
                    graph[j].append(A__       )
    return graph





def 	__a     (      A__			:  int       ):
    return {
        i: [j for j in range(A__       ) if i != j] for i in range(A__       )
    }


if __name__ == "__main__":
    import doctest

    doctest.testmod()


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







   '''simple docstring'''




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





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

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

       SCREAMING_SNAKE_CASE										=   self.get_config()

       return config, pixel_values, labels





   def      _snake_case		(       self					:			Dict			):
       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      _snake_case		(       self					:			List[str]     , __lowerCamelCase					:			Union[str, Any]     , __lowerCamelCase					:			Tuple     , __lowerCamelCase					:			List[Any]			):
       SCREAMING_SNAKE_CASE										=   SwiftFormerModel(config=__lowerCamelCase			)
       model.to(__lowerCamelCase			)
       model.eval()
       SCREAMING_SNAKE_CASE										=   model(__lowerCamelCase			)
       self.parent.assertEqual(result.last_hidden_state.shape     , (self.batch_size, self.embed_dims[-1], 7, 7)			)





   def      _snake_case		(       self					:			Dict     , __lowerCamelCase					:			int     , __lowerCamelCase					:			Any     , __lowerCamelCase					:			Optional[int]			):
       SCREAMING_SNAKE_CASE										=   self.num_labels
       SCREAMING_SNAKE_CASE										=   SwiftFormerForImageClassification(__lowerCamelCase			)
       model.to(__lowerCamelCase			)
       model.eval()
       SCREAMING_SNAKE_CASE										=   model(__lowerCamelCase     , labels=__lowerCamelCase			)
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.num_labels)			)

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

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





   def      _snake_case		(       self					:			int			):
       ((SCREAMING_SNAKE_CASE)							,	(SCREAMING_SNAKE_CASE)							,	(SCREAMING_SNAKE_CASE))										=   self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE										=   {"pixel_values": pixel_values}
       return config, inputs_dict





@require_torch
class 			_SCREAMING_SNAKE_CASE (   __snake_case					,       __snake_case					,       unittest.TestCase		):







   '''simple docstring'''




   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      _snake_case		(       self					:			int			):
       SCREAMING_SNAKE_CASE										=   SwiftFormerModelTester(self			)
       SCREAMING_SNAKE_CASE										=   ConfigTester(
           self     , config_class=__lowerCamelCase     , has_text_modality=__lowerCamelCase     , hidden_size=37     , num_attention_heads=12     , num_hidden_layers=12     , )





   def      _snake_case		(       self					:			List[Any]			):
       self.config_tester.run_common_tests()





   @unittest.skip(reason="SwiftFormer does not use inputs_embeds"			)
   def      _snake_case		(       self					:			Optional[int]			):
       pass





   def      _snake_case		(       self					:			Optional[int]			):
       SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs_for_common()

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





   def      _snake_case		(       self					:			List[Any]			):
       SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs_for_common()

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

           SCREAMING_SNAKE_CASE										=   ["pixel_values"]
           self.assertListEqual(arg_names[:1]     , __lowerCamelCase			)





   def      _snake_case		(       self					:			Union[str, Any]			):
       SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCamelCase			)





   def      _snake_case		(       self					:			int			):
       SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase			)





   @slow
   def      _snake_case		(       self					:			Tuple			):
       for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           SCREAMING_SNAKE_CASE										=   SwiftFormerModel.from_pretrained(__lowerCamelCase			)
           self.assertIsNotNone(__lowerCamelCase			)





   @unittest.skip(reason="SwiftFormer does not output attentions"			)
   def      _snake_case		(       self					:			Union[str, Any]			):
       pass





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

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

           SCREAMING_SNAKE_CASE										=   outputs.hidden_states

           SCREAMING_SNAKE_CASE										=   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										=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           SCREAMING_SNAKE_CASE										=   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										=   True

           check_hidden_states_output(__lowerCamelCase     , __lowerCamelCase     , __lowerCamelCase			)





   def      _snake_case		(       self					:			List[Any]			):
       def _config_zero_init(__lowerCamelCase					:			List[Any]			):
           SCREAMING_SNAKE_CASE										=   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										=   _config_zero_init(getattr(__lowerCamelCase     , __lowerCamelCase			)			)
                   setattr(__lowerCamelCase     , __lowerCamelCase     , __lowerCamelCase			)
           return configs_no_init

       SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   self.model_tester.prepare_config_and_inputs_for_common()

       SCREAMING_SNAKE_CASE										=   _config_zero_init(__lowerCamelCase			)
       for model_class in self.all_model_classes:
           SCREAMING_SNAKE_CASE										=   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      _snake_case		(       self					:			str			):
       pass





def 	__a     (      ):
    SCREAMING_SNAKE_CASE										=   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
    return image





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







   '''simple docstring'''




   @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					:			List[Any]			):
       SCREAMING_SNAKE_CASE										=   SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs"			).to(__lowerCamelCase			)

       SCREAMING_SNAKE_CASE										=   self.default_image_processor
       SCREAMING_SNAKE_CASE										=   prepare_img()
       SCREAMING_SNAKE_CASE										=   image_processor(images=__lowerCamelCase     , return_tensors="pt"			).to(__lowerCamelCase			)

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

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

       SCREAMING_SNAKE_CASE										=   torch.tensor([[-2.17_03e00, 2.11_07e00, -2.08_11e00]]			).to(__lowerCamelCase			)
       self.assertTrue(torch.allclose(outputs.logits[0, :3]     , __lowerCamelCase     , atol=1e-4			)			)