


'''simple docstring'''






import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import BlenderbotSmallConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
		import os

		# The slow tests are often failing with OOM error on GPU
		# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
		# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
		__UpperCAmelCase					       =							'''platform'''

		import jax
		import jax.numpy as jnp

		from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import (
		    FlaxBlenderbotSmallForConditionalGeneration,
		    FlaxBlenderbotSmallModel,
		    shift_tokens_right,
		)


def       _snake_case     (  A				,					A				,					A=None				,					A=None				,					A=None				,					A=None				,					A=None				,					A=None				,					)		->					Tuple:
							if attention_mask is None:
														lowerCAmelCase__      =			np.where(input_ids != config.pad_token_id				,					1				,					0 )
							if decoder_attention_mask is None:
														lowerCAmelCase__      =			np.where(decoder_input_ids != config.pad_token_id				,					1				,					0 )
							if head_mask is None:
														lowerCAmelCase__      =			np.ones((config.encoder_layers, config.encoder_attention_heads) )
							if decoder_head_mask is None:
														lowerCAmelCase__      =			np.ones((config.decoder_layers, config.decoder_attention_heads) )
							if cross_attn_head_mask is None:
														lowerCAmelCase__      =			np.ones((config.decoder_layers, config.decoder_attention_heads) )
							return {
							    "input_ids": input_ids,
							    "decoder_input_ids": decoder_input_ids,
							    "attention_mask": attention_mask,
							    "decoder_attention_mask": attention_mask,
							}




class 	a__       :





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_      ,					lowerCamelCase_=13      ,					lowerCamelCase_=7      ,					lowerCamelCase_=True      ,					lowerCamelCase_=False      ,					lowerCamelCase_=99      ,					lowerCamelCase_=16      ,					lowerCamelCase_=2      ,					lowerCamelCase_=4      ,					lowerCamelCase_=4      ,					lowerCamelCase_="gelu"      ,					lowerCamelCase_=0.1      ,					lowerCamelCase_=0.1      ,					lowerCamelCase_=32      ,					lowerCamelCase_=2      ,					lowerCamelCase_=1      ,					lowerCamelCase_=0      ,					lowerCamelCase_=0.02      ,					) ->							Optional[Any]:
														lowerCAmelCase__      =			parent
														lowerCAmelCase__      =			batch_size
														lowerCAmelCase__      =			seq_length
														lowerCAmelCase__      =			is_training
														lowerCAmelCase__      =			use_labels
														lowerCAmelCase__      =			vocab_size
														lowerCAmelCase__      =			hidden_size
														lowerCAmelCase__      =			num_hidden_layers
														lowerCAmelCase__      =			num_attention_heads
														lowerCAmelCase__      =			intermediate_size
														lowerCAmelCase__      =			hidden_act
														lowerCAmelCase__      =			hidden_dropout_prob
														lowerCAmelCase__      =			attention_probs_dropout_prob
														lowerCAmelCase__      =			max_position_embeddings
														lowerCAmelCase__      =			eos_token_id
														lowerCAmelCase__      =			pad_token_id
														lowerCAmelCase__      =			bos_token_id
														lowerCAmelCase__      =			initializer_range







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							str:
														lowerCAmelCase__      =			np.clip(ids_tensor([self.batch_size, self.seq_length - 1]      ,					self.vocab_size     )      ,					3      ,					self.vocab_size     )
														lowerCAmelCase__      =			np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)      ,					dtype=np.intaa     ))      ,					-1     )

														lowerCAmelCase__      =			shift_tokens_right(lowerCamelCase_      ,					1      ,					2     )

														lowerCAmelCase__      =			BlenderbotSmallConfig(
														    vocab_size=self.vocab_size      ,					d_model=self.hidden_size      ,					encoder_layers=self.num_hidden_layers      ,					decoder_layers=self.num_hidden_layers      ,					encoder_attention_heads=self.num_attention_heads      ,					decoder_attention_heads=self.num_attention_heads      ,					encoder_ffn_dim=self.intermediate_size      ,					decoder_ffn_dim=self.intermediate_size      ,					dropout=self.hidden_dropout_prob      ,					attention_dropout=self.attention_probs_dropout_prob      ,					max_position_embeddings=self.max_position_embeddings      ,					eos_token_id=self.eos_token_id      ,					bos_token_id=self.bos_token_id      ,					pad_token_id=self.pad_token_id      ,					initializer_range=self.initializer_range      ,					use_cache=lowerCamelCase_      ,					)
														lowerCAmelCase__      =			prepare_blenderbot_inputs_dict(lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_     )
														return config, inputs_dict







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							List[Any]:
														lowerCAmelCase__     ,      lowerCAmelCase__      =			self.prepare_config_and_inputs()
														return config, inputs_dict







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_     ) ->							List[str]:
														lowerCAmelCase__      =			20
														lowerCAmelCase__      =			model_class_name(lowerCamelCase_     )

														lowerCAmelCase__      =			model.encode(inputs_dict['''input_ids''']     )

														lowerCAmelCase__     ,      lowerCAmelCase__      =			(
														    inputs_dict['''decoder_input_ids'''],
														    inputs_dict['''decoder_attention_mask'''],
														)

														lowerCAmelCase__      =			model.init_cache(decoder_input_ids.shape[0]      ,					lowerCamelCase_      ,					lowerCamelCase_     )
														lowerCAmelCase__      =			jnp.ones((decoder_input_ids.shape[0], max_decoder_length)      ,					dtype='''i4'''     )

														lowerCAmelCase__      =			jnp.broadcast_to(
														    jnp.arange(decoder_input_ids.shape[-1] - 1     )[None, :]      ,					(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)      ,					)
														lowerCAmelCase__      =			model.decode(
														    decoder_input_ids[:, :-1]      ,					lowerCamelCase_      ,					decoder_attention_mask=lowerCamelCase_      ,					past_key_values=lowerCamelCase_      ,					decoder_position_ids=lowerCamelCase_      ,					)

														lowerCAmelCase__      =			jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]      ,					dtype='''i4'''     )
														lowerCAmelCase__      =			model.decode(
														    decoder_input_ids[:, -1:]      ,					lowerCamelCase_      ,					decoder_attention_mask=lowerCamelCase_      ,					past_key_values=outputs_cache.past_key_values      ,					decoder_position_ids=lowerCamelCase_      ,					)

														lowerCAmelCase__      =			model.decode(lowerCamelCase_      ,					lowerCamelCase_     )

														lowerCAmelCase__      =			np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])     )     )
														self.parent.assertTrue(diff < 1e-3      ,					msg=F"""Max diff is {diff}"""     )







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_     ) ->							List[str]:
														lowerCAmelCase__      =			20
														lowerCAmelCase__      =			model_class_name(lowerCamelCase_     )

														lowerCAmelCase__      =			model.encode(inputs_dict['''input_ids''']     )

														lowerCAmelCase__     ,      lowerCAmelCase__      =			(
														    inputs_dict['''decoder_input_ids'''],
														    inputs_dict['''decoder_attention_mask'''],
														)

														lowerCAmelCase__      =			jnp.concatenate(
														    [
														        decoder_attention_mask,
														        jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])     ),
														    ]      ,					axis=-1      ,					)

														lowerCAmelCase__      =			model.init_cache(decoder_input_ids.shape[0]      ,					lowerCamelCase_      ,					lowerCamelCase_     )
														lowerCAmelCase__      =			jnp.broadcast_to(
														    jnp.arange(decoder_input_ids.shape[-1] - 1     )[None, :]      ,					(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)      ,					)

														lowerCAmelCase__      =			model.decode(
														    decoder_input_ids[:, :-1]      ,					lowerCamelCase_      ,					decoder_attention_mask=lowerCamelCase_      ,					past_key_values=lowerCamelCase_      ,					decoder_position_ids=lowerCamelCase_      ,					)
														lowerCAmelCase__      =			jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]      ,					dtype='''i4'''     )
														lowerCAmelCase__      =			model.decode(
														    decoder_input_ids[:, -1:]      ,					lowerCamelCase_      ,					past_key_values=outputs_cache.past_key_values      ,					decoder_attention_mask=lowerCamelCase_      ,					decoder_position_ids=lowerCamelCase_      ,					)

														lowerCAmelCase__      =			model.decode(lowerCamelCase_      ,					lowerCamelCase_      ,					decoder_attention_mask=lowerCamelCase_     )

														lowerCAmelCase__      =			np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])     )     )
														self.parent.assertTrue(diff < 1e-3      ,					msg=F"""Max diff is {diff}"""     )




@require_flax
class 	a__       (							unittest.TestCase						):





							'''simple docstring'''






							lowercase__    :     int					=   9_9







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Tuple:
														lowerCAmelCase__      =			np.array(
														    [
														        [71, 82, 18, 33, 46, 91, 2],
														        [68, 34, 26, 58, 30, 82, 2],
														        [5, 97, 17, 39, 94, 40, 2],
														        [76, 83, 94, 25, 70, 78, 2],
														        [87, 59, 41, 35, 48, 66, 2],
														        [55, 13, 16, 58, 5, 2, 1],  # note padding
														        [64, 27, 31, 51, 12, 75, 2],
														        [52, 64, 86, 17, 83, 39, 2],
														        [48, 61, 9, 24, 71, 82, 2],
														        [26, 1, 60, 48, 22, 13, 2],
														        [21, 5, 62, 28, 14, 76, 2],
														        [45, 98, 37, 86, 59, 48, 2],
														        [70, 70, 50, 9, 28, 0, 2],
														    ]      ,					dtype=np.intaa      ,					)

														lowerCAmelCase__      =			input_ids.shape[0]
														lowerCAmelCase__      =			BlenderbotSmallConfig(
														    vocab_size=self.vocab_size      ,					d_model=24      ,					encoder_layers=2      ,					decoder_layers=2      ,					encoder_attention_heads=2      ,					decoder_attention_heads=2      ,					encoder_ffn_dim=32      ,					decoder_ffn_dim=32      ,					max_position_embeddings=48      ,					eos_token_id=2      ,					pad_token_id=1      ,					bos_token_id=0      ,					)
														return config, input_ids, batch_size







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							List[str]:
														lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__      =			self._get_config_and_data()
														lowerCAmelCase__      =			FlaxBlenderbotSmallForConditionalGeneration(lowerCamelCase_     )
														lowerCAmelCase__      =			lm_model(input_ids=lowerCamelCase_     )
														lowerCAmelCase__      =			(batch_size, input_ids.shape[1], config.vocab_size)
														self.assertEqual(outputs['''logits'''].shape      ,					lowerCamelCase_     )







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							List[str]:
														lowerCAmelCase__      =			BlenderbotSmallConfig(
														    vocab_size=self.vocab_size      ,					d_model=14      ,					encoder_layers=2      ,					decoder_layers=2      ,					encoder_attention_heads=2      ,					decoder_attention_heads=2      ,					encoder_ffn_dim=8      ,					decoder_ffn_dim=8      ,					max_position_embeddings=48      ,					)
														lowerCAmelCase__      =			FlaxBlenderbotSmallForConditionalGeneration(lowerCamelCase_     )
														lowerCAmelCase__      =			np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]]      ,					dtype=np.intaa     )
														lowerCAmelCase__      =			np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]]      ,					dtype=np.intaa     )
														lowerCAmelCase__      =			lm_model(input_ids=lowerCamelCase_      ,					decoder_input_ids=lowerCamelCase_     )
														lowerCAmelCase__      =			(*summary.shape, config.vocab_size)
														self.assertEqual(outputs['''logits'''].shape      ,					lowerCamelCase_     )







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							str:
														lowerCAmelCase__      =			np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]]      ,					dtype=np.intaa     )
														lowerCAmelCase__      =			shift_tokens_right(lowerCamelCase_      ,					1      ,					2     )
														lowerCAmelCase__      =			np.equal(lowerCamelCase_      ,					1     ).astype(np.floataa     ).sum()
														lowerCAmelCase__      =			np.equal(lowerCamelCase_      ,					1     ).astype(np.floataa     ).sum()
														self.assertEqual(shifted.shape      ,					input_ids.shape     )
														self.assertEqual(lowerCamelCase_      ,					n_pad_before - 1     )
														self.assertTrue(np.equal(shifted[:, 0]      ,					2     ).all()     )




@require_flax
class 	a__       (							a__       ,       unittest.TestCase       ,       a__						):





							'''simple docstring'''






							lowercase__    :     Optional[int]					=   True
							lowercase__    :     Tuple					=   (
							    (
							        FlaxBlenderbotSmallModel,
							        FlaxBlenderbotSmallForConditionalGeneration,
							    )
							    if is_flax_available()
							    else ()
							)
							lowercase__    :     List[Any]					=   (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else ()







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							List[str]:
														lowerCAmelCase__      =			FlaxBlenderbotSmallModelTester(self     )







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Union[str, Any]:
														lowerCAmelCase__     ,      lowerCAmelCase__      =			self.model_tester.prepare_config_and_inputs()
														for model_class in self.all_model_classes:
																					self.model_tester.check_use_cache_forward(lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_     )







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Dict:
														lowerCAmelCase__     ,      lowerCAmelCase__      =			self.model_tester.prepare_config_and_inputs()
														for model_class in self.all_model_classes:
																					self.model_tester.check_use_cache_forward_with_attn_mask(lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_     )







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Tuple:
														lowerCAmelCase__     ,      lowerCAmelCase__      =			self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					with self.subTest(model_class.__name__     ):
																												lowerCAmelCase__      =			self._prepare_for_class(lowerCamelCase_      ,					lowerCamelCase_     )
																												lowerCAmelCase__      =			model_class(lowerCamelCase_     )

																												@jax.jit
																												def encode_jitted(lowerCamelCase_      ,					lowerCamelCase_=None      ,					**lowerCamelCase_     ):
																																			return model.encode(input_ids=lowerCamelCase_      ,					attention_mask=lowerCamelCase_     )

																												with self.subTest('''JIT Enabled'''     ):
																																			lowerCAmelCase__      =			encode_jitted(**lowerCamelCase_     ).to_tuple()

																												with self.subTest('''JIT Disabled'''     ):
																																			with jax.disable_jit():
																																										lowerCAmelCase__      =			encode_jitted(**lowerCamelCase_     ).to_tuple()

																												self.assertEqual(len(lowerCamelCase_     )      ,					len(lowerCamelCase_     )     )
																												for jitted_output, output in zip(lowerCamelCase_      ,					lowerCamelCase_     ):
																																			self.assertEqual(jitted_output.shape      ,					output.shape     )







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Optional[Any]:
														lowerCAmelCase__     ,      lowerCAmelCase__      =			self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					with self.subTest(model_class.__name__     ):
																												lowerCAmelCase__      =			model_class(lowerCamelCase_     )
																												lowerCAmelCase__      =			model.encode(inputs_dict['''input_ids''']      ,					inputs_dict['''attention_mask''']     )

																												lowerCAmelCase__      =			{
																												    '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''],
																												    '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''],
																												    '''encoder_outputs''': encoder_outputs,
																												}

																												@jax.jit
																												def decode_jitted(lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_     ):
																																			return model.decode(
																																			    decoder_input_ids=lowerCamelCase_      ,					decoder_attention_mask=lowerCamelCase_      ,					encoder_outputs=lowerCamelCase_      ,					)

																												with self.subTest('''JIT Enabled'''     ):
																																			lowerCAmelCase__      =			decode_jitted(**lowerCamelCase_     ).to_tuple()

																												with self.subTest('''JIT Disabled'''     ):
																																			with jax.disable_jit():
																																										lowerCAmelCase__      =			decode_jitted(**lowerCamelCase_     ).to_tuple()

																												self.assertEqual(len(lowerCamelCase_     )      ,					len(lowerCamelCase_     )     )
																												for jitted_output, output in zip(lowerCamelCase_      ,					lowerCamelCase_     ):
																																			self.assertEqual(jitted_output.shape      ,					output.shape     )







							@slow
							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Union[str, Any]:
														for model_class_name in self.all_model_classes:
																					lowerCAmelCase__      =			model_class_name.from_pretrained('''facebook/blenderbot_small-90M'''     )
																					# FlaxBlenderbotForSequenceClassification expects eos token in input_ids
																					lowerCAmelCase__      =			np.ones((1, 1)     ) * model.config.eos_token_id
																					lowerCAmelCase__      =			model(lowerCamelCase_     )
																					self.assertIsNotNone(lowerCamelCase_     )



'''simple docstring'''






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 ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


__UpperCAmelCase					       =							logging.get_logger(__name__)

# General docstring
__UpperCAmelCase					       =							'''RegNetConfig'''

# Base docstring
__UpperCAmelCase					       =							'''facebook/regnet-y-040'''
__UpperCAmelCase					       =							[1, 1_088, 7, 7]

# Image classification docstring
__UpperCAmelCase					       =							'''facebook/regnet-y-040'''
__UpperCAmelCase					       =							'''tabby, tabby cat'''

__UpperCAmelCase					       =							[
    '''facebook/regnet-y-040''',
    # See all regnet models at https://huggingface.co/models?filter=regnet
]




class 	a__       (							nn.Module						):





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_ = 3      ,					lowerCamelCase_ = 1      ,					lowerCamelCase_ = 1      ,					lowerCamelCase_ = "relu"      ,					) ->							int:
														super().__init__()
														lowerCAmelCase__      =			nn.Convad(
														    lowerCamelCase_      ,					lowerCamelCase_      ,					kernel_size=lowerCamelCase_      ,					stride=lowerCamelCase_      ,					padding=kernel_size // 2      ,					groups=lowerCamelCase_      ,					bias=lowerCamelCase_      ,					)
														lowerCAmelCase__      =			nn.BatchNormad(lowerCamelCase_     )
														lowerCAmelCase__      =			ACTaFN[activation] if activation is not None else nn.Identity()







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_     ) ->							Dict:
														lowerCAmelCase__      =			self.convolution(lowerCamelCase_     )
														lowerCAmelCase__      =			self.normalization(lowerCamelCase_     )
														lowerCAmelCase__      =			self.activation(lowerCamelCase_     )
														return hidden_state




class 	a__       (							nn.Module						):





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_     ) ->							Optional[Any]:
														super().__init__()
														lowerCAmelCase__      =			RegNetConvLayer(
														    config.num_channels      ,					config.embedding_size      ,					kernel_size=3      ,					stride=2      ,					activation=config.hidden_act     )
														lowerCAmelCase__      =			config.num_channels







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_     ) ->							int:
														lowerCAmelCase__      =			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.'''     )
														lowerCAmelCase__      =			self.embedder(lowerCamelCase_     )
														return hidden_state




class 	a__       (							nn.Module						):





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_ = 2     ) ->							Any:
														super().__init__()
														lowerCAmelCase__      =			nn.Convad(lowerCamelCase_      ,					lowerCamelCase_      ,					kernel_size=1      ,					stride=lowerCamelCase_      ,					bias=lowerCamelCase_     )
														lowerCAmelCase__      =			nn.BatchNormad(lowerCamelCase_     )







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_     ) ->							Tensor:
														lowerCAmelCase__      =			self.convolution(lowerCamelCase_     )
														lowerCAmelCase__      =			self.normalization(lowerCamelCase_     )
														return hidden_state




class 	a__       (							nn.Module						):





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_      ,					lowerCamelCase_     ) ->							List[Any]:
														super().__init__()

														lowerCAmelCase__      =			nn.AdaptiveAvgPoolad((1, 1)     )
														lowerCAmelCase__      =			nn.Sequential(
														    nn.Convad(lowerCamelCase_      ,					lowerCamelCase_      ,					kernel_size=1     )      ,					nn.ReLU()      ,					nn.Convad(lowerCamelCase_      ,					lowerCamelCase_      ,					kernel_size=1     )      ,					nn.Sigmoid()      ,					)







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_     ) ->							int:
														# b c h w -> b c 1 1
														lowerCAmelCase__      =			self.pooler(lowerCamelCase_     )
														lowerCAmelCase__      =			self.attention(lowerCamelCase_     )
														lowerCAmelCase__      =			hidden_state * attention
														return hidden_state




class 	a__       (							nn.Module						):





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_ = 1     ) ->							Optional[int]:
														super().__init__()
														lowerCAmelCase__      =			in_channels != out_channels or stride != 1
														lowerCAmelCase__      =			max(1      ,					out_channels // config.groups_width     )
														lowerCAmelCase__      =			(
														    RegNetShortCut(lowerCamelCase_      ,					lowerCamelCase_      ,					stride=lowerCamelCase_     ) if should_apply_shortcut else nn.Identity()
														)
														lowerCAmelCase__      =			nn.Sequential(
														    RegNetConvLayer(lowerCamelCase_      ,					lowerCamelCase_      ,					kernel_size=1      ,					activation=config.hidden_act     )      ,					RegNetConvLayer(lowerCamelCase_      ,					lowerCamelCase_      ,					stride=lowerCamelCase_      ,					groups=lowerCamelCase_      ,					activation=config.hidden_act     )      ,					RegNetConvLayer(lowerCamelCase_      ,					lowerCamelCase_      ,					kernel_size=1      ,					activation=lowerCamelCase_     )      ,					)
														lowerCAmelCase__      =			ACTaFN[config.hidden_act]







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_     ) ->							List[str]:
														lowerCAmelCase__      =			hidden_state
														lowerCAmelCase__      =			self.layer(lowerCamelCase_     )
														lowerCAmelCase__      =			self.shortcut(lowerCamelCase_     )
														hidden_state += residual
														lowerCAmelCase__      =			self.activation(lowerCamelCase_     )
														return hidden_state




class 	a__       (							nn.Module						):





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_ = 1     ) ->							Optional[int]:
														super().__init__()
														lowerCAmelCase__      =			in_channels != out_channels or stride != 1
														lowerCAmelCase__      =			max(1      ,					out_channels // config.groups_width     )
														lowerCAmelCase__      =			(
														    RegNetShortCut(lowerCamelCase_      ,					lowerCamelCase_      ,					stride=lowerCamelCase_     ) if should_apply_shortcut else nn.Identity()
														)
														lowerCAmelCase__      =			nn.Sequential(
														    RegNetConvLayer(lowerCamelCase_      ,					lowerCamelCase_      ,					kernel_size=1      ,					activation=config.hidden_act     )      ,					RegNetConvLayer(lowerCamelCase_      ,					lowerCamelCase_      ,					stride=lowerCamelCase_      ,					groups=lowerCamelCase_      ,					activation=config.hidden_act     )      ,					RegNetSELayer(lowerCamelCase_      ,					reduced_channels=int(round(in_channels / 4     )     )     )      ,					RegNetConvLayer(lowerCamelCase_      ,					lowerCamelCase_      ,					kernel_size=1      ,					activation=lowerCamelCase_     )      ,					)
														lowerCAmelCase__      =			ACTaFN[config.hidden_act]







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_     ) ->							Union[str, Any]:
														lowerCAmelCase__      =			hidden_state
														lowerCAmelCase__      =			self.layer(lowerCamelCase_     )
														lowerCAmelCase__      =			self.shortcut(lowerCamelCase_     )
														hidden_state += residual
														lowerCAmelCase__      =			self.activation(lowerCamelCase_     )
														return hidden_state




class 	a__       (							nn.Module						):





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_ = 2      ,					lowerCamelCase_ = 2      ,					) ->							Dict:
														super().__init__()

														lowerCAmelCase__      =			RegNetXLayer if config.layer_type == '''x''' else RegNetYLayer

														lowerCAmelCase__      =			nn.Sequential(
														    # downsampling is done in the first layer with stride of 2
														    layer(
														        lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					stride=lowerCamelCase_      ,					)      ,					*[layer(lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_     ) for _ in range(depth - 1     )]      ,					)







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_     ) ->							List[str]:
														lowerCAmelCase__      =			self.layers(lowerCamelCase_     )
														return hidden_state




class 	a__       (							nn.Module						):





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_     ) ->							Optional[int]:
														super().__init__()
														lowerCAmelCase__      =			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(
														    RegNetStage(
														        lowerCamelCase_      ,					config.embedding_size      ,					config.hidden_sizes[0]      ,					stride=2 if config.downsample_in_first_stage else 1      ,					depth=config.depths[0]      ,					)     )
														lowerCAmelCase__      =			zip(config.hidden_sizes      ,					config.hidden_sizes[1:]     )
														for (in_channels, out_channels), depth in zip(lowerCamelCase_      ,					config.depths[1:]     ):
																					self.stages.append(RegNetStage(lowerCamelCase_      ,					lowerCamelCase_      ,					lowerCamelCase_      ,					depth=lowerCamelCase_     )     )







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_      ,					lowerCamelCase_ = False      ,					lowerCamelCase_ = True     ) ->							BaseModelOutputWithNoAttention:
														lowerCAmelCase__      =			() if output_hidden_states else None

														for stage_module in self.stages:
																					if output_hidden_states:
																												lowerCAmelCase__      =			hidden_states + (hidden_state,)

																					lowerCAmelCase__      =			stage_module(lowerCamelCase_     )

														if output_hidden_states:
																					lowerCAmelCase__      =			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=lowerCamelCase_      ,					hidden_states=lowerCamelCase_     )




class 	a__       (							a__						):





							'''simple docstring'''






							lowercase__    :     List[Any]					=   RegNetConfig
							lowercase__    :     Tuple					=   "regnet"
							lowercase__    :     List[str]					=   "pixel_values"
							lowercase__    :     Tuple					=   True







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_     ) ->							int:
														if isinstance(lowerCamelCase_      ,					nn.Convad     ):
																					nn.init.kaiming_normal_(module.weight      ,					mode='''fan_out'''      ,					nonlinearity='''relu'''     )
														elif isinstance(lowerCamelCase_      ,					(nn.BatchNormad, nn.GroupNorm)     ):
																					nn.init.constant_(module.weight      ,					1     )
																					nn.init.constant_(module.bias      ,					0     )







							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_      ,					lowerCamelCase_=False     ) ->							int:
														if isinstance(lowerCamelCase_      ,					lowerCamelCase_     ):
																					lowerCAmelCase__      =			value

__UpperCAmelCase					       =							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 ([`RegNetConfig`]): 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.
'''

__UpperCAmelCase					       =							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 [`~file_utils.ModelOutput`] instead of a plain tuple.
'''




@add_start_docstrings(
    "The bare RegNet model outputting raw features without any specific head on top."       ,       a__       ,       )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class 	a__       (							a__						):





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_     ) ->							Optional[int]:
														super().__init__(lowerCamelCase_     )
														lowerCAmelCase__      =			config
														lowerCAmelCase__      =			RegNetEmbeddings(lowerCamelCase_     )
														lowerCAmelCase__      =			RegNetEncoder(lowerCamelCase_     )
														lowerCAmelCase__      =			nn.AdaptiveAvgPoolad((1, 1)     )
														# Initialize weights and apply final processing
														self.post_init()







							@add_start_docstrings_to_model_forward(lowerCamelCase_     )
							@add_code_sample_docstrings(
							    checkpoint=_CHECKPOINT_FOR_DOC      ,					output_type=lowerCamelCase_      ,					config_class=_CONFIG_FOR_DOC      ,					modality='''vision'''      ,					expected_output=_EXPECTED_OUTPUT_SHAPE      ,					)
							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_      ,					lowerCamelCase_ = None      ,					lowerCamelCase_ = None     ) ->							BaseModelOutputWithPoolingAndNoAttention:
														lowerCAmelCase__      =			(
														    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
														)
														lowerCAmelCase__      =			return_dict if return_dict is not None else self.config.use_return_dict

														lowerCAmelCase__      =			self.embedder(lowerCamelCase_     )

														lowerCAmelCase__      =			self.encoder(
														    lowerCamelCase_      ,					output_hidden_states=lowerCamelCase_      ,					return_dict=lowerCamelCase_     )

														lowerCAmelCase__      =			encoder_outputs[0]

														lowerCAmelCase__      =			self.pooler(lowerCamelCase_     )

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

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




@add_start_docstrings(
    "\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "       ,       a__       ,       )
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class 	a__       (							a__						):





							'''simple docstring'''






							def __init__(	self      ,					lowerCamelCase_     ) ->							Optional[Any]:
														super().__init__(lowerCamelCase_     )
														lowerCAmelCase__      =			config.num_labels
														lowerCAmelCase__      =			RegNetModel(lowerCamelCase_     )
														# classification head
														lowerCAmelCase__      =			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(lowerCamelCase_     )
							@add_code_sample_docstrings(
							    checkpoint=_IMAGE_CLASS_CHECKPOINT      ,					output_type=lowerCamelCase_      ,					config_class=_CONFIG_FOR_DOC      ,					expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT      ,					)
							def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_ = None      ,					lowerCamelCase_ = None      ,					lowerCamelCase_ = None      ,					lowerCamelCase_ = None      ,					) ->							ImageClassifierOutputWithNoAttention:
														lowerCAmelCase__      =			return_dict if return_dict is not None else self.config.use_return_dict

														lowerCAmelCase__      =			self.regnet(lowerCamelCase_      ,					output_hidden_states=lowerCamelCase_      ,					return_dict=lowerCamelCase_     )

														lowerCAmelCase__      =			outputs.pooler_output if return_dict else outputs[1]

														lowerCAmelCase__      =			self.classifier(lowerCamelCase_     )

														lowerCAmelCase__      =			None

														if labels is not None:
																					if self.config.problem_type is None:
																												if self.num_labels == 1:
																																			lowerCAmelCase__      =			'''regression'''
																												elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																																			lowerCAmelCase__      =			'''single_label_classification'''
																												else:
																																			lowerCAmelCase__      =			'''multi_label_classification'''
																					if self.config.problem_type == "regression":
																												lowerCAmelCase__      =			MSELoss()
																												if self.num_labels == 1:
																																			lowerCAmelCase__      =			loss_fct(logits.squeeze()      ,					labels.squeeze()     )
																												else:
																																			lowerCAmelCase__      =			loss_fct(lowerCamelCase_      ,					lowerCamelCase_     )
																					elif self.config.problem_type == "single_label_classification":
																												lowerCAmelCase__      =			CrossEntropyLoss()
																												lowerCAmelCase__      =			loss_fct(logits.view(-1      ,					self.num_labels     )      ,					labels.view(-1     )     )
																					elif self.config.problem_type == "multi_label_classification":
																												lowerCAmelCase__      =			BCEWithLogitsLoss()
																												lowerCAmelCase__      =			loss_fct(lowerCamelCase_      ,					lowerCamelCase_     )

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

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