






'''simple docstring'''

import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_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 torch import nn

      from transformers import MaskFormerSwinBackbone
      from transformers.models.maskformer import MaskFormerSwinModel




class     A    :






 """simple docstring"""





 def __init__(							self			,     __lowerCAmelCase			,     __lowerCAmelCase=13			,     __lowerCAmelCase=32			,     __lowerCAmelCase=2			,     __lowerCAmelCase=3			,     __lowerCAmelCase=16			,     __lowerCAmelCase=[1, 2, 1]			,     __lowerCAmelCase=[2, 2, 4]			,     __lowerCAmelCase=2			,     __lowerCAmelCase=2.0			,     __lowerCAmelCase=True			,     __lowerCAmelCase=0.0			,     __lowerCAmelCase=0.0			,     __lowerCAmelCase=0.1			,     __lowerCAmelCase="gelu"			,     __lowerCAmelCase=False			,     __lowerCAmelCase=True			,     __lowerCAmelCase=0.02			,     __lowerCAmelCase=1E-5			,     __lowerCAmelCase=True			,     __lowerCAmelCase=None			,     __lowerCAmelCase=True			,     __lowerCAmelCase=10			,     __lowerCAmelCase=8			,     __lowerCAmelCase=["stage1", "stage2", "stage3"]			,     __lowerCAmelCase=[1, 2, 3]			,     ):
       UpperCamelCase_				:   Union[str, Any]					    =							parent
       UpperCamelCase_				:   List[Any]					    =							batch_size
       UpperCamelCase_				:   List[Any]					    =							image_size
       UpperCamelCase_				:   int					    =							patch_size
       UpperCamelCase_				:   int					    =							num_channels
       UpperCamelCase_				:   Union[str, Any]					    =							embed_dim
       UpperCamelCase_				:   Dict					    =							depths
       UpperCamelCase_				:   List[Any]					    =							num_heads
       UpperCamelCase_				:   Union[str, Any]					    =							window_size
       UpperCamelCase_				:   Optional[Any]					    =							mlp_ratio
       UpperCamelCase_				:   Any					    =							qkv_bias
       UpperCamelCase_				:   str					    =							hidden_dropout_prob
       UpperCamelCase_				:   Optional[Any]					    =							attention_probs_dropout_prob
       UpperCamelCase_				:   int					    =							drop_path_rate
       UpperCamelCase_				:   Optional[Any]					    =							hidden_act
       UpperCamelCase_				:   Any					    =							use_absolute_embeddings
       UpperCamelCase_				:   List[Any]					    =							patch_norm
       UpperCamelCase_				:   Optional[Any]					    =							layer_norm_eps
       UpperCamelCase_				:   Union[str, Any]					    =							initializer_range
       UpperCamelCase_				:   List[str]					    =							is_training
       UpperCamelCase_				:   List[Any]					    =							scope
       UpperCamelCase_				:   Tuple					    =							use_labels
       UpperCamelCase_				:   str					    =							type_sequence_label_size
       UpperCamelCase_				:   Dict					    =							encoder_stride
       UpperCamelCase_				:   Any					    =							out_features
       UpperCamelCase_				:   str					    =							out_indices
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Any					    =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

       UpperCamelCase_				:   List[Any]					    =							None
       if self.use_labels:
             UpperCamelCase_				:   Dict					    =							ids_tensor([self.batch_size]			,     self.type_sequence_label_size )

       UpperCamelCase_				:   Optional[int]					    =							self.get_config()

       return config, pixel_values, labels
 def   _UpperCAmelCase       (							self ):
       return MaskFormerSwinConfig(
           image_size=self.image_size			,     patch_size=self.patch_size			,     num_channels=self.num_channels			,     embed_dim=self.embed_dim			,     depths=self.depths			,     num_heads=self.num_heads			,     window_size=self.window_size			,     mlp_ratio=self.mlp_ratio			,     qkv_bias=self.qkv_bias			,     hidden_dropout_prob=self.hidden_dropout_prob			,     attention_probs_dropout_prob=self.attention_probs_dropout_prob			,     drop_path_rate=self.drop_path_rate			,     hidden_act=self.hidden_act			,     use_absolute_embeddings=self.use_absolute_embeddings			,     path_norm=self.patch_norm			,     layer_norm_eps=self.layer_norm_eps			,     initializer_range=self.initializer_range			,     encoder_stride=self.encoder_stride			,     out_features=self.out_features			,     out_indices=self.out_indices			,     )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Union[str, Any]					    =							MaskFormerSwinModel(config=__lowerCAmelCase )
       model.to(__lowerCAmelCase )
       model.eval()
       UpperCamelCase_				:   Tuple					    =							model(__lowerCAmelCase )

       UpperCamelCase_				:   Optional[int]					    =							((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
       UpperCamelCase_				:   Optional[int]					    =							int(config.embed_dim * 2 ** (len(config.depths ) - 1) )

       self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, expected_seq_len, expected_dim) )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_				:   str					    =							MaskFormerSwinBackbone(config=__lowerCAmelCase )
       model.to(__lowerCAmelCase )
       model.eval()
       UpperCamelCase_				:   int					    =							model(__lowerCAmelCase )

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps )			,     len(config.out_features ) )
       self.parent.assertListEqual(list(result.feature_maps[0].shape )			,     [13, 16, 16, 16] )

       # verify channels
       self.parent.assertEqual(len(model.channels )			,     len(config.out_features ) )
       self.parent.assertListEqual(model.channels			,     [16, 32, 64] )

       # verify ValueError
       with self.parent.assertRaises(__lowerCAmelCase ):
             UpperCamelCase_				:   str					    =							["""stem"""]
             UpperCamelCase_				:   int					    =							MaskFormerSwinBackbone(config=__lowerCAmelCase )





 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[int]					    =							self.prepare_config_and_inputs()
       UpperCamelCase_    ,			UpperCamelCase_    ,			UpperCamelCase_				:   Optional[Any]					    =							config_and_inputs
       UpperCamelCase_				:   Tuple					    =							{"""pixel_values""": pixel_values}
       return config, inputs_dict






@require_torch
class     A    (      SCREAMING_SNAKE_CASE__,   SCREAMING_SNAKE_CASE__,   unittest.TestCase						):






 """simple docstring"""





 __a			:						Dict      =						(
     (
         MaskFormerSwinModel,
         MaskFormerSwinBackbone,
     )
     if is_torch_available()
     else ()
 )
 __a			:						List[str]      =						{'''feature-extraction''': MaskFormerSwinModel} if is_torch_available() else {}
 __a			:						int      =						False
 __a			:						Any      =						False
 __a			:						Tuple      =						False
 __a			:						Any      =						False
 __a			:						List[str]      =						False
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[Any]					    =							MaskFormerSwinModelTester(self )
       UpperCamelCase_				:   List[Any]					    =							ConfigTester(self			,     config_class=__lowerCAmelCase			,     embed_dim=37 )
 @require_torch_multi_gpu
 @unittest.skip(
     reason=(
         """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with"""
         """ `nn.DataParallel`"""
     ) )
 def   _UpperCAmelCase       (							self ):
       pass
 def   _UpperCAmelCase       (							self ):
       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   _UpperCAmelCase       (							self ):
       return
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[int]					    =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCAmelCase )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Dict					    =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*__lowerCAmelCase )
 @unittest.skip("""Swin does not use inputs_embeds""" )
 def   _UpperCAmelCase       (							self ):
       pass
 @unittest.skip("""Swin does not support feedforward chunking""" )
 def   _UpperCAmelCase       (							self ):
       pass
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_    ,			UpperCamelCase_				:   Union[str, Any]					    =							self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             UpperCamelCase_				:   Union[str, Any]					    =							model_class(__lowerCAmelCase )
             self.assertIsInstance(model.get_input_embeddings()			,     (nn.Module) )
             UpperCamelCase_				:   Tuple					    =							model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(__lowerCAmelCase			,     nn.Linear ) )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_    ,			UpperCamelCase_				:   str					    =							self.model_tester.prepare_config_and_inputs_for_common()

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

             UpperCamelCase_				:   Any					    =							["""pixel_values"""]
             self.assertListEqual(arg_names[:1]			,     __lowerCAmelCase )
 @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions""" )
 def   _UpperCAmelCase       (							self ):
       pass
 @unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone""" )
 def   _UpperCAmelCase       (							self ):
       pass
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_				:   str					    =							model_class(__lowerCAmelCase )
       model.to(__lowerCAmelCase )
       model.eval()

       with torch.no_grad():
             UpperCamelCase_				:   Tuple					    =							model(**self._prepare_for_class(__lowerCAmelCase			,     __lowerCAmelCase ) )

       UpperCamelCase_				:   str					    =							outputs.hidden_states

       UpperCamelCase_				:   Optional[Any]					    =							getattr(
           self.model_tester			,     """expected_num_hidden_layers"""			,     len(self.model_tester.depths ) + 1 )
       self.assertEqual(len(__lowerCAmelCase )			,     __lowerCAmelCase )

       # Swin has a different seq_length
       UpperCamelCase_				:   Optional[Any]					    =							(
           config.patch_size
           if isinstance(config.patch_size			,     collections.abc.Iterable )
           else (config.patch_size, config.patch_size)
       )

       UpperCamelCase_				:   Optional[int]					    =							(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

       self.assertListEqual(
           list(hidden_states[0].shape[-2:] )			,     [num_patches, self.model_tester.embed_dim]			,     )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_    ,			UpperCamelCase_				:   Optional[int]					    =							self.model_tester.prepare_config_and_inputs_for_common()

       UpperCamelCase_				:   Any					    =							(
           self.model_tester.image_size
           if isinstance(self.model_tester.image_size			,     collections.abc.Iterable )
           else (self.model_tester.image_size, self.model_tester.image_size)
       )

       for model_class in self.all_model_classes:
             UpperCamelCase_				:   Tuple					    =							True
             self.check_hidden_states_output(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             UpperCamelCase_				:   Dict					    =							True

             self.check_hidden_states_output(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_    ,			UpperCamelCase_				:   Union[str, Any]					    =							self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase_				:   Optional[int]					    =							3

       UpperCamelCase_				:   List[Any]					    =							(
           self.model_tester.image_size
           if isinstance(self.model_tester.image_size			,     collections.abc.Iterable )
           else (self.model_tester.image_size, self.model_tester.image_size)
       )
       UpperCamelCase_				:   Any					    =							(
           config.patch_size
           if isinstance(config.patch_size			,     collections.abc.Iterable )
           else (config.patch_size, config.patch_size)
       )

       UpperCamelCase_				:   Optional[int]					    =							image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
       UpperCamelCase_				:   Optional[Any]					    =							image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

       for model_class in self.all_model_classes:
             UpperCamelCase_				:   List[Any]					    =							True
             self.check_hidden_states_output(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     (padded_height, padded_width) )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             UpperCamelCase_				:   Any					    =							True
             self.check_hidden_states_output(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     (padded_height, padded_width) )
 @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints""" )
 def   _UpperCAmelCase       (							self ):
       pass
 @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" )
 def   _UpperCAmelCase       (							self ):
       pass
 @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" )
 def   _UpperCAmelCase       (							self ):
       pass





 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_    ,			UpperCamelCase_				:   Any					    =							self.model_tester.prepare_config_and_inputs_for_common()

       def set_nan_tensor_to_zero(__lowerCAmelCase ):
             UpperCamelCase_				:   str					    =							0
             return t

       def check_equivalence(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase={} ):
             with torch.no_grad():
                   UpperCamelCase_				:   List[str]					    =							model(**__lowerCAmelCase			,     return_dict=__lowerCAmelCase			,     **__lowerCAmelCase )
                   UpperCamelCase_				:   Tuple					    =							model(**__lowerCAmelCase			,     return_dict=__lowerCAmelCase			,     **__lowerCAmelCase ).to_tuple()

                   def recursive_check(__lowerCAmelCase			,     __lowerCAmelCase ):
                         if isinstance(__lowerCAmelCase			,     (List, Tuple) ):
                               for tuple_iterable_value, dict_iterable_value in zip(__lowerCAmelCase			,     __lowerCAmelCase ):
                                     recursive_check(__lowerCAmelCase			,     __lowerCAmelCase )
                         elif isinstance(__lowerCAmelCase			,     __lowerCAmelCase ):
                               for tuple_iterable_value, dict_iterable_value in zip(
                                   tuple_object.values()			,     dict_object.values() ):
                                     recursive_check(__lowerCAmelCase			,     __lowerCAmelCase )
                         elif tuple_object is None:
                               return
                         else:
                               self.assertTrue(
                                   torch.allclose(
                                       set_nan_tensor_to_zero(__lowerCAmelCase )			,     set_nan_tensor_to_zero(__lowerCAmelCase )			,     atol=1E-5 )			,     msg=(
                                       """Tuple and dict output are not equal. Difference:"""
                                       F" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:"
                                       F" {torch.isnan(__lowerCAmelCase ).any()} and `inf`: {torch.isinf(__lowerCAmelCase )}. Dict has"
                                       F" `nan`: {torch.isnan(__lowerCAmelCase ).any()} and `inf`: {torch.isinf(__lowerCAmelCase )}."
                                   )			,     )

                   recursive_check(__lowerCAmelCase			,     __lowerCAmelCase )

       for model_class in self.all_model_classes:
             UpperCamelCase_				:   Any					    =							model_class(__lowerCAmelCase )
             model.to(__lowerCAmelCase )
             model.eval()

             UpperCamelCase_				:   Tuple					    =							self._prepare_for_class(__lowerCAmelCase			,     __lowerCAmelCase )
             UpperCamelCase_				:   List[str]					    =							self._prepare_for_class(__lowerCAmelCase			,     __lowerCAmelCase )
             check_equivalence(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase )

             UpperCamelCase_				:   Dict					    =							self._prepare_for_class(__lowerCAmelCase			,     __lowerCAmelCase			,     return_labels=__lowerCAmelCase )
             UpperCamelCase_				:   Union[str, Any]					    =							self._prepare_for_class(__lowerCAmelCase			,     __lowerCAmelCase			,     return_labels=__lowerCAmelCase )
             check_equivalence(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase )

             UpperCamelCase_				:   Dict					    =							self._prepare_for_class(__lowerCAmelCase			,     __lowerCAmelCase )
             UpperCamelCase_				:   Union[str, Any]					    =							self._prepare_for_class(__lowerCAmelCase			,     __lowerCAmelCase )
             check_equivalence(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     {"""output_hidden_states""": True} )

             UpperCamelCase_				:   Dict					    =							self._prepare_for_class(__lowerCAmelCase			,     __lowerCAmelCase			,     return_labels=__lowerCAmelCase )
             UpperCamelCase_				:   Optional[int]					    =							self._prepare_for_class(__lowerCAmelCase			,     __lowerCAmelCase			,     return_labels=__lowerCAmelCase )
             check_equivalence(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     {"""output_hidden_states""": True} )






@require_torch
class     A    (      unittest.TestCase,   SCREAMING_SNAKE_CASE__						):






 """simple docstring"""





 __a			:						List[str]      =						(MaskFormerSwinBackbone,) if is_torch_available() else ()
 __a			:						Optional[Any]      =						MaskFormerSwinConfig
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   List[Any]					    =							MaskFormerSwinModelTester(self )





 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_    ,			UpperCamelCase_				:   List[str]					    =							self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase_				:   Optional[Any]					    =							inputs_dict["""pixel_values"""].shape[0]

       for backbone_class in self.all_model_classes:
             UpperCamelCase_				:   List[str]					    =							backbone_class(__lowerCAmelCase )
             backbone.to(__lowerCAmelCase )
             backbone.eval()

             UpperCamelCase_				:   List[Any]					    =							backbone(**__lowerCAmelCase )

             # Test default outputs and verify feature maps
             self.assertIsInstance(outputs.feature_maps			,     __lowerCAmelCase )
             self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) )
             for feature_map, n_channels in zip(outputs.feature_maps			,     backbone.channels ):
                   self.assertTrue(feature_map.shape[:2]			,     (batch_size, n_channels) )
             self.assertIsNone(outputs.hidden_states )
             self.assertIsNone(outputs.attentions )

             # Test output_hidden_states=True
             UpperCamelCase_				:   Optional[int]					    =							backbone(**__lowerCAmelCase			,     output_hidden_states=__lowerCAmelCase )
             self.assertIsNotNone(outputs.hidden_states )
             self.assertTrue(len(outputs.hidden_states )			,     len(backbone.stage_names ) )
             # We skip the stem layer
             for hidden_states, n_channels in zip(outputs.hidden_states[1:]			,     backbone.channels ):
                   for hidden_state in hidden_states:
                         # Hidden states are in the format (batch_size, (height * width), n_channels)
                         UpperCamelCase_    ,			UpperCamelCase_    ,			UpperCamelCase_				:   str					    =							hidden_state.shape
                         self.assertTrue((h_batch_size, h_n_channels)			,     (batch_size, n_channels) )

            # Test output_attentions=True
             if self.has_attentions:
                   UpperCamelCase_				:   List[str]					    =							backbone(**__lowerCAmelCase			,     output_attentions=__lowerCAmelCase )
                   self.assertIsNotNone(outputs.attentions )














'''simple docstring'''

from __future__ import annotations

import os
from typing import Any

import requests

UpperCamelCase							="https://api.github.com"

# https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user
UpperCamelCase							=BASE_URL + "/user"

# https://github.com/settings/tokens
UpperCamelCase							=os.environ.get("USER_TOKEN", "")



def 							snake_case					(     a_							: str	)       ->				dict[Any, Any]:





      """simple docstring"""

      UpperCamelCase_				:   Tuple					    =							{
          """Authorization""": f"token {auth_token}",
          """Accept""": """application/vnd.github.v3+json""",
      }
      return requests.get(a_    ,   headers=a_	).json()


if __name__ == "__main__":  # pragma: no cover
      if USER_TOKEN:
            for key, value in fetch_github_info(USER_TOKEN).items():
                  print(f"{key}: {value}")
      else:
            raise ValueError("'USER_TOKEN' field cannot be empty.")






