
from __future__ import annotations

import random
import unittest

from transformers import TransfoXLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers import (
       TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
       TFTransfoXLForSequenceClassification,
       TFTransfoXLLMHeadModel,
       TFTransfoXLModel,
   )





class     __UpperCamelCase :






     """simple docstring"""







     def __init__(				self							:							Optional[int]     ,						_A							:							List[str]     ,						):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	str					=		parent
       __SCREAMING_SNAKE_CASE      :	int					=		13
       __SCREAMING_SNAKE_CASE      :	Any					=		7
       __SCREAMING_SNAKE_CASE      :	List[str]					=		30
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		self.seq_length + self.mem_len
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		15
       __SCREAMING_SNAKE_CASE      :	Any					=		True
       __SCREAMING_SNAKE_CASE      :	Dict					=		True
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		99
       __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		[10, 50, 80]
       __SCREAMING_SNAKE_CASE      :	int					=		32
       __SCREAMING_SNAKE_CASE      :	int					=		32
       __SCREAMING_SNAKE_CASE      :	Dict					=		4
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		8
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		128
       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		2
       __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		2
       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		None
       __SCREAMING_SNAKE_CASE      :	Dict					=		1
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		0
       __SCREAMING_SNAKE_CASE      :	int					=		3
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		self.vocab_size - 1
       __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		0.01



     def  UpperCAmelCase__							(				self							:							Optional[int] ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		ids_tensor([self.batch_size, self.seq_length]     ,						self.vocab_size )
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		ids_tensor([self.batch_size, self.seq_length]     ,						self.vocab_size )

       __SCREAMING_SNAKE_CASE      :	List[Any]					=		None
       if self.use_labels:
         __SCREAMING_SNAKE_CASE      :	List[Any]					=		ids_tensor([self.batch_size, self.seq_length]     ,						self.vocab_size )

       __SCREAMING_SNAKE_CASE      :	List[str]					=		TransfoXLConfig(
           vocab_size=self.vocab_size     ,						mem_len=self.mem_len     ,						clamp_len=self.clamp_len     ,						cutoffs=self.cutoffs     ,						d_model=self.hidden_size     ,						d_embed=self.d_embed     ,						n_head=self.num_attention_heads     ,						d_head=self.d_head     ,						d_inner=self.d_inner     ,						div_val=self.div_val     ,						n_layer=self.num_hidden_layers     ,						eos_token_id=self.eos_token_id     ,						pad_token_id=self.vocab_size - 1     ,						init_range=self.init_range     ,						num_labels=self.num_labels     ,						)

       return (config, input_ids_a, input_ids_a, lm_labels)



     def  UpperCAmelCase__							(				self							:							int ):







       """simple docstring"""




       random.seed(self.seed )
       tf.random.set_seed(self.seed )



     def  UpperCAmelCase__							(				self							:							List[str]     ,						_A							:							Dict     ,						_A							:							str     ,						_A							:							Any     ,						_A							:							List[str] ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Dict					=		TFTransfoXLModel(_A )

       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	Dict					=		model(_A ).to_tuple()

       __SCREAMING_SNAKE_CASE      :	Tuple					=		{'''input_ids''': input_ids_a, '''mems''': mems_a}

       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	Optional[Any]					=		model(_A ).to_tuple()

       self.parent.assertEqual(hidden_states_a.shape     ,						(self.batch_size, self.seq_length, self.hidden_size) )
       self.parent.assertEqual(hidden_states_a.shape     ,						(self.batch_size, self.seq_length, self.hidden_size) )
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]     ,						[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers     ,						)
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]     ,						[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers     ,						)



     def  UpperCAmelCase__							(				self							:							Dict     ,						_A							:							int     ,						_A							:							List[str]     ,						_A							:							int     ,						_A							:							int ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	List[str]					=		TFTransfoXLLMHeadModel(_A )

       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	Optional[Any]					=		model(_A ).to_tuple()

       __SCREAMING_SNAKE_CASE      :	Any					=		{'''input_ids''': input_ids_a, '''labels''': lm_labels}
       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	Tuple					=		model(_A ).to_tuple()

       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	Dict					=		model([input_ids_a, mems_a] ).to_tuple()

       __SCREAMING_SNAKE_CASE      :	int					=		{'''input_ids''': input_ids_a, '''mems''': mems_a, '''labels''': lm_labels}

       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	List[str]					=		model(_A ).to_tuple()

       self.parent.assertEqual(lm_logits_a.shape     ,						(self.batch_size, self.seq_length, self.vocab_size) )
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]     ,						[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers     ,						)

       self.parent.assertEqual(lm_logits_a.shape     ,						(self.batch_size, self.seq_length, self.vocab_size) )
       self.parent.assertListEqual(
           [mem.shape for mem in mems_a]     ,						[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers     ,						)



     def  UpperCAmelCase__							(				self							:							Dict     ,						_A							:							Tuple     ,						_A							:							int     ,						_A							:							Dict     ,						_A							:							Tuple ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Tuple					=		TFTransfoXLForSequenceClassification(_A )
       __SCREAMING_SNAKE_CASE      :	int					=		model(_A )
       self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.num_labels) )




     def  UpperCAmelCase__							(				self							:							str ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Tuple					=		self.prepare_config_and_inputs()
       ((__SCREAMING_SNAKE_CASE),		(__SCREAMING_SNAKE_CASE),		(__SCREAMING_SNAKE_CASE),		(__SCREAMING_SNAKE_CASE))      :	Optional[Any]					=		config_and_inputs
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		{'''input_ids''': input_ids_a}
       return config, inputs_dict






@require_tf
class     __UpperCamelCase (							lowerCAmelCase__ ,						lowerCAmelCase__ ,						unittest.TestCase       ):






     """simple docstring"""







     lowerCAmelCase_							   =			(
         (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
     )
     lowerCAmelCase_							   =			() if is_tf_available() else ()
     lowerCAmelCase_							   =			(
         {
             '''feature-extraction''': TFTransfoXLModel,
             '''text-classification''': TFTransfoXLForSequenceClassification,
             '''text-generation''': TFTransfoXLLMHeadModel,
             '''zero-shot''': TFTransfoXLForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented
     lowerCAmelCase_							   =			False
     lowerCAmelCase_							   =			False
     lowerCAmelCase_							   =			False
     lowerCAmelCase_							   =			False



     def  UpperCAmelCase__							(				self							:							Dict     ,						_A							:							Union[str, Any]     ,						_A							:							List[Any]     ,						_A							:							Optional[Any]     ,						_A							:							Optional[Any]     ,						_A							:							Union[str, Any] ):







       """simple docstring"""




       if pipeline_test_casse_name == "TextGenerationPipelineTests":
         # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
         # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple
         # tokenizer.
         return True

       return False



     def  UpperCAmelCase__							(				self							:							str ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		TFTransfoXLModelTester(self )
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		ConfigTester(self     ,						config_class=_A     ,						d_embed=37 )



     def  UpperCAmelCase__							(				self							:							int ):







       """simple docstring"""




       self.config_tester.run_common_tests()



     def  UpperCAmelCase__							(				self							:							Optional[int] ):







       """simple docstring"""




       self.model_tester.set_seed()
       __SCREAMING_SNAKE_CASE      :	Tuple					=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_model(*_A )



     def  UpperCAmelCase__							(				self							:							int ):







       """simple docstring"""




       self.model_tester.set_seed()
       __SCREAMING_SNAKE_CASE      :	str					=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_lm_head(*_A )



     def  UpperCAmelCase__							(				self							:							Optional[int] ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Any					=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*_A )



     def  UpperCAmelCase__							(				self							:							List[Any] ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	Dict					=		self.model_tester.prepare_config_and_inputs_for_common()
       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		[TFTransfoXLForSequenceClassification]

       for model_class in self.all_model_classes:
         __SCREAMING_SNAKE_CASE      :	Dict					=		model_class(_A )
         assert isinstance(model.get_input_embeddings()     ,						tf.keras.layers.Layer )
         if model_class in list_other_models_with_output_ebd:
           __SCREAMING_SNAKE_CASE      :	List[Any]					=		model.get_output_embeddings()
           assert isinstance(_A     ,						tf.keras.layers.Layer )
           __SCREAMING_SNAKE_CASE      :	Any					=		model.get_bias()
           assert name is None
         else:
           __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		model.get_output_embeddings()
           assert x is None
           __SCREAMING_SNAKE_CASE      :	Dict					=		model.get_bias()
           assert name is None



     def  UpperCAmelCase__							(				self							:							int ):







       """simple docstring"""




       pass



     @slow
     def  UpperCAmelCase__							(				self							:							Optional[Any] ):







       """simple docstring"""




       for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		TFTransfoXLModel.from_pretrained(_A )
         self.assertIsNotNone(_A )




     @unittest.skip(reason='''This model doesn\'t play well with fit() due to not returning a single loss.''' )
     def  UpperCAmelCase__							(				self							:							int ):







       """simple docstring"""




       pass






@require_tf
class     __UpperCamelCase (							unittest.TestCase       ):






     """simple docstring"""







     @unittest.skip('''Skip test until #12651 is resolved.''' )
     @slow
     def  UpperCAmelCase__							(				self							:							Any ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	int					=		TFTransfoXLLMHeadModel.from_pretrained('''transfo-xl-wt103''' )
       # fmt: off
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		tf.convert_to_tensor([[33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0]]     ,						dtype=tf.intaa )  # noqa: E231
       # fmt: on
       #  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>

       # fmt: off
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		[33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0,33,1,1857,2,1,1009,4,1109,1_1739,4762,358,5,25,245,28,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,0]  # noqa: E231
       # fmt: on
       #  In 1991, the remains of Russian Tsar Nicholas II and his family (
       #  except for Alexei and Maria ) are discovered. The voice of 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. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
       # Nicholas II and his family were discovered. The voice of <unk> young son,
       # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>

       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		model.generate(_A     ,						max_length=200     ,						do_sample=_A )
       self.assertListEqual(output_ids[0].numpy().tolist()     ,						_A )








from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


lowerCamelCase__       		=  logging.get_logger(__name__)

# General docstring
lowerCamelCase__       		=  """ResNetConfig"""

# Base docstring
lowerCamelCase__       		=  """microsoft/resnet-50"""
lowerCamelCase__       		=  [1, 2048, 7, 7]

# Image classification docstring
lowerCamelCase__       		=  """microsoft/resnet-50"""
lowerCamelCase__       		=  """tiger cat"""

lowerCamelCase__       		=  [
    """microsoft/resnet-50""",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]




class       snake_case__ (				nn.Module):

       '''simple docstring'''



       def __init__(				self      ,    a__      ,    a__      ,    a__ = 3      ,    a__ = 1      ,    a__ = "relu"     )			->   Optional[Any]:






            '''simple docstring'''





            super().__init__()
            __snake_case      :Dict 							=    nn.Convad(
                a__      ,    a__      ,    kernel_size=a__      ,    stride=a__      ,    padding=kernel_size // 2      ,    bias=a__     )
            __snake_case      :str 							=    nn.BatchNormad(a__     )
            __snake_case      :List[Any] 							=    ACTaFN[activation] if activation is not None else nn.Identity()



       def        __lowercase    (				self      ,    a__     )			->   Tensor:






            '''simple docstring'''





            __snake_case      :int 							=    self.convolution(a__     )
            __snake_case      :Any 							=    self.normalization(a__     )
            __snake_case      :Optional[int] 							=    self.activation(a__     )
            return hidden_state




class       snake_case__ (				nn.Module):

       '''simple docstring'''



       def __init__(				self      ,    a__     )			->   str:






            '''simple docstring'''





            super().__init__()
            __snake_case      :Dict 							=    ResNetConvLayer(
                config.num_channels      ,    config.embedding_size      ,    kernel_size=7      ,    stride=2      ,    activation=config.hidden_act     )
            __snake_case      :List[Any] 							=    nn.MaxPoolad(kernel_size=3      ,    stride=2      ,    padding=1     )
            __snake_case      :Tuple 							=    config.num_channels



       def        __lowercase    (				self      ,    a__     )			->   Tensor:






            '''simple docstring'''





            __snake_case      :Optional[Any] 							=    pixel_values.shape[1]
            if num_channels != self.num_channels:
                 raise ValueError(
                     """Make sure that the channel dimension of the pixel values match with the one set in the configuration."""     )
            __snake_case      :Optional[int] 							=    self.embedder(a__     )
            __snake_case      :int 							=    self.pooler(a__     )
            return embedding




class       snake_case__ (				nn.Module):

       '''simple docstring'''



       def __init__(				self      ,    a__      ,    a__      ,    a__ = 2     )			->   Optional[Any]:






            '''simple docstring'''





            super().__init__()
            __snake_case      :Optional[Any] 							=    nn.Convad(a__      ,    a__      ,    kernel_size=1      ,    stride=a__      ,    bias=a__     )
            __snake_case      :Tuple 							=    nn.BatchNormad(a__     )



       def        __lowercase    (				self      ,    a__     )			->   Tensor:






            '''simple docstring'''





            __snake_case      :Any 							=    self.convolution(a__     )
            __snake_case      :str 							=    self.normalization(a__     )
            return hidden_state




class       snake_case__ (				nn.Module):

       '''simple docstring'''



       def __init__(				self      ,    a__      ,    a__      ,    a__ = 1      ,    a__ = "relu"     )			->   List[str]:






            '''simple docstring'''





            super().__init__()
            __snake_case      :int 							=    in_channels != out_channels or stride != 1
            __snake_case      :Tuple 							=    (
                ResNetShortCut(a__      ,    a__      ,    stride=a__     ) if should_apply_shortcut else nn.Identity()
            )
            __snake_case      :Optional[int] 							=    nn.Sequential(
                ResNetConvLayer(a__      ,    a__      ,    stride=a__     )      ,    ResNetConvLayer(a__      ,    a__      ,    activation=a__     )      ,    )
            __snake_case      :Union[str, Any] 							=    ACTaFN[activation]



       def        __lowercase    (				self      ,    a__     )			->   Union[str, Any]:






            '''simple docstring'''





            __snake_case      :int 							=    hidden_state
            __snake_case      :Dict 							=    self.layer(a__     )
            __snake_case      :Any 							=    self.shortcut(a__     )
            hidden_state += residual
            __snake_case      :List[Any] 							=    self.activation(a__     )
            return hidden_state




class       snake_case__ (				nn.Module):

       '''simple docstring'''



       def __init__(				self      ,    a__      ,    a__      ,    a__ = 1      ,    a__ = "relu"      ,    a__ = 4     )			->   List[Any]:






            '''simple docstring'''





            super().__init__()
            __snake_case      :Optional[int] 							=    in_channels != out_channels or stride != 1
            __snake_case      :List[Any] 							=    out_channels // reduction
            __snake_case      :List[str] 							=    (
                ResNetShortCut(a__      ,    a__      ,    stride=a__     ) if should_apply_shortcut else nn.Identity()
            )
            __snake_case      :int 							=    nn.Sequential(
                ResNetConvLayer(a__      ,    a__      ,    kernel_size=1     )      ,    ResNetConvLayer(a__      ,    a__      ,    stride=a__     )      ,    ResNetConvLayer(a__      ,    a__      ,    kernel_size=1      ,    activation=a__     )      ,    )
            __snake_case      :Dict 							=    ACTaFN[activation]



       def        __lowercase    (				self      ,    a__     )			->   Any:






            '''simple docstring'''





            __snake_case      :List[str] 							=    hidden_state
            __snake_case      :List[Any] 							=    self.layer(a__     )
            __snake_case      :List[Any] 							=    self.shortcut(a__     )
            hidden_state += residual
            __snake_case      :Optional[Any] 							=    self.activation(a__     )
            return hidden_state




class       snake_case__ (				nn.Module):

       '''simple docstring'''



       def __init__(				self      ,    a__      ,    a__      ,    a__      ,    a__ = 2      ,    a__ = 2      ,    )			->   Any:






            '''simple docstring'''





            super().__init__()

            __snake_case      :Optional[int] 							=    ResNetBottleNeckLayer if config.layer_type == """bottleneck""" else ResNetBasicLayer

            __snake_case      :Tuple 							=    nn.Sequential(
                # downsampling is done in the first layer with stride of 2
                layer(a__      ,    a__      ,    stride=a__      ,    activation=config.hidden_act     )      ,    *[layer(a__      ,    a__      ,    activation=config.hidden_act     ) for _ in range(depth - 1     )]      ,    )



       def        __lowercase    (				self      ,    a__     )			->   Tensor:






            '''simple docstring'''





            __snake_case      :Union[str, Any] 							=    input
            for layer in self.layers:
                 __snake_case      :str 							=    layer(a__     )
            return hidden_state




class       snake_case__ (				nn.Module):

       '''simple docstring'''



       def __init__(				self      ,    a__     )			->   Union[str, Any]:






            '''simple docstring'''





            super().__init__()
            __snake_case      :Optional[int] 							=    nn.ModuleList([]     )
            # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
            self.stages.append(
                ResNetStage(
                    a__      ,    config.embedding_size      ,    config.hidden_sizes[0]      ,    stride=2 if config.downsample_in_first_stage else 1      ,    depth=config.depths[0]      ,    )     )
            __snake_case      :Tuple 							=    zip(config.hidden_sizes      ,    config.hidden_sizes[1:]     )
            for (in_channels, out_channels), depth in zip(a__      ,    config.depths[1:]     ):
                 self.stages.append(ResNetStage(a__      ,    a__      ,    a__      ,    depth=a__     )     )



       def        __lowercase    (				self      ,    a__      ,    a__ = False      ,    a__ = True     )			->   BaseModelOutputWithNoAttention:






            '''simple docstring'''





            __snake_case      :Dict 							=    () if output_hidden_states else None

            for stage_module in self.stages:
                 if output_hidden_states:
                      __snake_case      :Optional[int] 							=    hidden_states + (hidden_state,)

                 __snake_case      :Tuple 							=    stage_module(a__     )

            if output_hidden_states:
                 __snake_case      :Optional[Any] 							=    hidden_states + (hidden_state,)

            if not return_dict:
                 return tuple(v for v in [hidden_state, hidden_states] if v is not None     )

            return BaseModelOutputWithNoAttention(
                last_hidden_state=a__      ,    hidden_states=a__      ,    )




class       snake_case__ (				lowercase_):

       '''simple docstring'''
       lowerCamelCase				:					List[Any]								=			ResNetConfig
       lowerCamelCase				:					Optional[Any]								=			"resnet"
       lowerCamelCase				:					str								=			"pixel_values"
       lowerCamelCase				:					Optional[int]								=			True



       def        __lowercase    (				self      ,    a__     )			->   Dict:






            '''simple docstring'''





            if isinstance(a__      ,    nn.Convad     ):
                 nn.init.kaiming_normal_(module.weight      ,    mode="""fan_out"""      ,    nonlinearity="""relu"""     )
            elif isinstance(a__      ,    (nn.BatchNormad, nn.GroupNorm)     ):
                 nn.init.constant_(module.weight      ,    1     )
                 nn.init.constant_(module.bias      ,    0     )



       def        __lowercase    (				self      ,    a__      ,    a__=False     )			->   Optional[int]:






            '''simple docstring'''





            if isinstance(a__      ,    a__     ):
                 __snake_case      :Union[str, Any] 							=    value
lowerCamelCase__       		=  R"""
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

lowerCamelCase__       		=  R"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""




@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."						,     lowercase_						,     )
class       snake_case__ (				lowercase_):

       '''simple docstring'''



       def __init__(				self      ,    a__     )			->   Tuple:






            '''simple docstring'''





            super().__init__(a__     )
            __snake_case      :int 							=    config
            __snake_case      :Any 							=    ResNetEmbeddings(a__     )
            __snake_case      :Dict 							=    ResNetEncoder(a__     )
            __snake_case      :Dict 							=    nn.AdaptiveAvgPoolad((1, 1)     )
            # Initialize weights and apply final processing
            self.post_init()



       @add_start_docstrings_to_model_forward(a__     )
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC      ,    output_type=a__      ,    config_class=_CONFIG_FOR_DOC      ,    modality="""vision"""      ,    expected_output=_EXPECTED_OUTPUT_SHAPE      ,    )
       def        __lowercase    (				self      ,    a__      ,    a__ = None      ,    a__ = None     )			->   BaseModelOutputWithPoolingAndNoAttention:






            '''simple docstring'''





            __snake_case      :List[str] 							=    (
                output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
            )
            __snake_case      :List[str] 							=    return_dict if return_dict is not None else self.config.use_return_dict

            __snake_case      :int 							=    self.embedder(a__     )

            __snake_case      :Any 							=    self.encoder(
                a__      ,    output_hidden_states=a__      ,    return_dict=a__     )

            __snake_case      :Any 							=    encoder_outputs[0]

            __snake_case      :int 							=    self.pooler(a__     )

            if not return_dict:
                 return (last_hidden_state, pooled_output) + encoder_outputs[1:]

            return BaseModelOutputWithPoolingAndNoAttention(
                last_hidden_state=a__      ,    pooler_output=a__      ,    hidden_states=encoder_outputs.hidden_states      ,    )




@add_start_docstrings(
    "\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "						,     lowercase_						,     )
class       snake_case__ (				lowercase_):

       '''simple docstring'''



       def __init__(				self      ,    a__     )			->   List[Any]:






            '''simple docstring'''





            super().__init__(a__     )
            __snake_case      :Union[str, Any] 							=    config.num_labels
            __snake_case      :Optional[int] 							=    ResNetModel(a__     )
            # classification head
            __snake_case      :List[str] 							=    nn.Sequential(
                nn.Flatten()      ,    nn.Linear(config.hidden_sizes[-1]      ,    config.num_labels     ) if config.num_labels > 0 else nn.Identity()      ,    )
            # initialize weights and apply final processing
            self.post_init()



       @add_start_docstrings_to_model_forward(a__     )
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT      ,    output_type=a__      ,    config_class=_CONFIG_FOR_DOC      ,    expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT      ,    )
       def        __lowercase    (				self      ,    a__ = None      ,    a__ = None      ,    a__ = None      ,    a__ = None      ,    )			->   ImageClassifierOutputWithNoAttention:






            '''simple docstring'''





            __snake_case      :Union[str, Any] 							=    return_dict if return_dict is not None else self.config.use_return_dict

            __snake_case      :Tuple 							=    self.resnet(a__      ,    output_hidden_states=a__      ,    return_dict=a__     )

            __snake_case      :Optional[Any] 							=    outputs.pooler_output if return_dict else outputs[1]

            __snake_case      :Optional[Any] 							=    self.classifier(a__     )

            __snake_case      :Any 							=    None

            if labels is not None:
                 if self.config.problem_type is None:
                      if self.num_labels == 1:
                           __snake_case      :List[Any] 							=    """regression"""
                      elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                           __snake_case      :List[Any] 							=    """single_label_classification"""
                      else:
                           __snake_case      :Union[str, Any] 							=    """multi_label_classification"""
                 if self.config.problem_type == "regression":
                      __snake_case      :Any 							=    MSELoss()
                      if self.num_labels == 1:
                           __snake_case      :Optional[Any] 							=    loss_fct(logits.squeeze()      ,    labels.squeeze()     )
                      else:
                           __snake_case      :Any 							=    loss_fct(a__      ,    a__     )
                 elif self.config.problem_type == "single_label_classification":
                      __snake_case      :int 							=    CrossEntropyLoss()
                      __snake_case      :List[Any] 							=    loss_fct(logits.view(-1      ,    self.num_labels     )      ,    labels.view(-1     )     )
                 elif self.config.problem_type == "multi_label_classification":
                      __snake_case      :List[str] 							=    BCEWithLogitsLoss()
                      __snake_case      :int 							=    loss_fct(a__      ,    a__     )

            if not return_dict:
                 __snake_case      :int 							=    (logits,) + outputs[2:]
                 return (loss,) + output if loss is not None else output

            return ImageClassifierOutputWithNoAttention(loss=a__      ,    logits=a__      ,    hidden_states=outputs.hidden_states     )




@add_start_docstrings(
    "\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    "						,     lowercase_						,     )
class       snake_case__ (				lowercase_						,     lowercase_):

       '''simple docstring'''



       def __init__(				self      ,    a__     )			->   int:






            '''simple docstring'''





            super().__init__(a__     )
            super()._init_backbone(a__     )

            __snake_case      :Optional[int] 							=    [config.embedding_size] + config.hidden_sizes
            __snake_case      :str 							=    ResNetEmbeddings(a__     )
            __snake_case      :Any 							=    ResNetEncoder(a__     )

            # initialize weights and apply final processing
            self.post_init()



       @add_start_docstrings_to_model_forward(a__     )
       @replace_return_docstrings(output_type=a__      ,    config_class=_CONFIG_FOR_DOC     )
       def        __lowercase    (				self      ,    a__      ,    a__ = None      ,    a__ = None     )			->   BackboneOutput:






            '''simple docstring'''





            __snake_case      :int 							=    return_dict if return_dict is not None else self.config.use_return_dict
            __snake_case      :Union[str, Any] 							=    (
                output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
            )

            __snake_case      :List[str] 							=    self.embedder(a__     )

            __snake_case      :List[Any] 							=    self.encoder(a__      ,    output_hidden_states=a__      ,    return_dict=a__     )

            __snake_case      :Optional[int] 							=    outputs.hidden_states

            __snake_case      :Tuple 							=    ()
            for idx, stage in enumerate(self.stage_names     ):
                 if stage in self.out_features:
                      feature_maps += (hidden_states[idx],)

            if not return_dict:
                 __snake_case      :Union[str, Any] 							=    (feature_maps,)
                 if output_hidden_states:
                      output += (outputs.hidden_states,)
                 return output

            return BackboneOutput(
                feature_maps=a__      ,    hidden_states=outputs.hidden_states if output_hidden_states else None      ,    attentions=a__      ,    )


