



import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
     import tensorflow as tf





class  lowerCamelCase__	(    enum.Enum):
     """simple docstring"""



     _A      =      0
     _A      =      1
     _A      =      2





@add_end_docstrings(UpperCAmelCase_)
class  lowerCamelCase__	(    UpperCAmelCase_):
     """simple docstring"""



     _A      =      '\n    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n    begging for his blessing. <eod> </s> <eos>\n    '







     def __init__(self					,      *__a					,      **__a     ):






           '''simple docstring'''



           super().__init__(*__a					,      **__a     )
           self.check_model_type(
               TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING     )
           if "prefix" not in self._preprocess_params:
                 # This is very specific. The logic is quite complex and needs to be done
                 # as a "default".
                 # It also defines both some preprocess_kwargs and generate_kwargs
                 # which is why we cannot put them in their respective methods.
                 lowerCamelCase             =		None
                 if self.model.config.prefix is not None:
                       lowerCamelCase             =		self.model.config.prefix
                 if prefix is None and self.model.__class__.__name__ in [
                     "XLNetLMHeadModel",
                     "TransfoXLLMHeadModel",
                     "TFXLNetLMHeadModel",
                     "TFTransfoXLLMHeadModel",
                 ]:
                       # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
                       lowerCamelCase             =		self.XL_PREFIX
                 if prefix is not None:
                       # Recalculate some generate_kwargs linked to prefix.
                       lowerCamelCase      ,				lowerCamelCase      ,				lowerCamelCase             =		self._sanitize_parameters(prefix=__a					,      **self._forward_params     )
                       lowerCamelCase             =		{**self._preprocess_params, **preprocess_params}
                       lowerCamelCase             =		{**self._forward_params, **forward_params}







     def     _a   (self					,      __a=None					,      __a=None					,      __a=None					,      __a=None					,      __a=None					,      __a=None					,      __a=None					,      __a=None					,      **__a					,      ):






           '''simple docstring'''



           lowerCamelCase             =		{}
           if prefix is not None:
                 lowerCamelCase             =		prefix
           if prefix:
                 lowerCamelCase             =		self.tokenizer(
                     __a					,      padding=__a					,      add_special_tokens=__a					,      return_tensors=self.framework     )
                 lowerCamelCase             =		prefix_inputs["input_ids"].shape[-1]

           if handle_long_generation is not None:
                 if handle_long_generation not in {"hole"}:
                       raise ValueError(
                           F"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"""
                           " [None, 'hole']"     )
                 lowerCamelCase             =		handle_long_generation

           preprocess_params.update(__a     )
           lowerCamelCase             =		generate_kwargs

           lowerCamelCase             =		{}
           if return_full_text is not None and return_type is None:
                 if return_text is not None:
                       raise ValueError("`return_text` is mutually exclusive with `return_full_text`"     )
                 if return_tensors is not None:
                       raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`"     )
                 lowerCamelCase             =		ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
           if return_tensors is not None and return_type is None:
                 if return_text is not None:
                       raise ValueError("`return_text` is mutually exclusive with `return_tensors`"     )
                 lowerCamelCase             =		ReturnType.TENSORS
           if return_type is not None:
                 lowerCamelCase             =		return_type
           if clean_up_tokenization_spaces is not None:
                 lowerCamelCase             =		clean_up_tokenization_spaces

           if stop_sequence is not None:
                 lowerCamelCase             =		self.tokenizer.encode(__a					,      add_special_tokens=__a     )
                 if len(__a     ) > 1:
                       warnings.warn(
                           "Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
                           " the stop sequence will be used as the stop sequence string in the interim."     )
                 lowerCamelCase             =		stop_sequence_ids[0]

           return preprocess_params, forward_params, postprocess_params







     def     _a   (self					,      *__a					,      **__a     ):






           '''simple docstring'''



           if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
                 kwargs.update({"add_space_before_punct_symbol": True}     )

           return super()._parse_and_tokenize(*__a					,      **__a     )







     def __call__(self					,      __a					,      **__a     ):






           '''simple docstring'''



           return super().__call__(__a					,      **__a     )







     def     _a   (self					,      __a					,      __a=""					,      __a=None					,      **__a     ):






           '''simple docstring'''



           lowerCamelCase             =		self.tokenizer(
               prefix + prompt_text					,      padding=__a					,      add_special_tokens=__a					,      return_tensors=self.framework     )
           lowerCamelCase             =		prompt_text

           if handle_long_generation == "hole":
                 lowerCamelCase             =		inputs["input_ids"].shape[-1]
                 if "max_new_tokens" in generate_kwargs:
                       lowerCamelCase             =		generate_kwargs["max_new_tokens"]
                 else:
                       lowerCamelCase             =		generate_kwargs.get("max_length"					,      self.model.config.max_length     ) - cur_len
                       if new_tokens < 0:
                             raise ValueError("We cannot infer how many new tokens are expected"     )
                 if cur_len + new_tokens > self.tokenizer.model_max_length:
                       lowerCamelCase             =		self.tokenizer.model_max_length - new_tokens
                       if keep_length <= 0:
                             raise ValueError(
                                 "We cannot use `hole` to handle this generation the number of desired tokens exceeds the"
                                 " models max length"     )

                       lowerCamelCase             =		inputs["input_ids"][:, -keep_length:]
                       if "attention_mask" in inputs:
                             lowerCamelCase             =		inputs["attention_mask"][:, -keep_length:]

           return inputs







     def     _a   (self					,      __a					,      **__a     ):






           '''simple docstring'''



           lowerCamelCase             =		model_inputs["input_ids"]
           lowerCamelCase             =		model_inputs.get("attention_mask"					,      __a     )
           # Allow empty prompts
           if input_ids.shape[1] == 0:
                 lowerCamelCase             =		None
                 lowerCamelCase             =		None
                 lowerCamelCase             =		1
           else:
                 lowerCamelCase             =		input_ids.shape[0]
           lowerCamelCase             =		model_inputs.pop("prompt_text"     )

           # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
           # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
           lowerCamelCase             =		generate_kwargs.pop("prefix_length"					,      0     )
           if prefix_length > 0:
                 lowerCamelCase             =		"max_new_tokens" in generate_kwargs or (
                     "generation_config" in generate_kwargs
                     and generate_kwargs["generation_config"].max_new_tokens is not None
                 )
                 if not has_max_new_tokens:
                       lowerCamelCase             =		generate_kwargs.get("max_length"     ) or self.model.config.max_length
                       generate_kwargs["max_length"] += prefix_length
                 lowerCamelCase             =		"min_new_tokens" in generate_kwargs or (
                     "generation_config" in generate_kwargs
                     and generate_kwargs["generation_config"].min_new_tokens is not None
                 )
                 if not has_min_new_tokens and "min_length" in generate_kwargs:
                       generate_kwargs["min_length"] += prefix_length

        # BS x SL
           lowerCamelCase             =		self.model.generate(input_ids=__a					,      attention_mask=__a					,      **__a     )
           lowerCamelCase             =		generated_sequence.shape[0]
           if self.framework == "pt":
                 lowerCamelCase             =		generated_sequence.reshape(__a					,      out_b // in_b					,      *generated_sequence.shape[1:]     )
           elif self.framework == "tf":
                 lowerCamelCase             =		tf.reshape(__a					,      (in_b, out_b // in_b, *generated_sequence.shape[1:])     )
           return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}







     def     _a   (self					,      __a					,      __a=ReturnType.FULL_TEXT					,      __a=True     ):






           '''simple docstring'''



           lowerCamelCase             =		model_outputs["generated_sequence"][0]
           lowerCamelCase             =		model_outputs["input_ids"]
           lowerCamelCase             =		model_outputs["prompt_text"]
           lowerCamelCase             =		generated_sequence.numpy().tolist()
           lowerCamelCase             =		[]
           for sequence in generated_sequence:
                 if return_type == ReturnType.TENSORS:
                       lowerCamelCase             =		{"generated_token_ids": sequence}
                 elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
                       # Decode text
                       lowerCamelCase             =		self.tokenizer.decode(
                           __a					,      skip_special_tokens=__a					,      clean_up_tokenization_spaces=__a					,      )

                       # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
                       if input_ids is None:
                             lowerCamelCase             =		0
                       else:
                             lowerCamelCase             =		len(
                                 self.tokenizer.decode(
                                     input_ids[0]					,      skip_special_tokens=__a					,      clean_up_tokenization_spaces=__a					,      )     )

                       if return_type == ReturnType.FULL_TEXT:
                             lowerCamelCase             =		prompt_text + text[prompt_length:]
                       else:
                             lowerCamelCase             =		text[prompt_length:]

                       lowerCamelCase             =		{"generated_text": all_text}
                 records.append(__a     )

           return records




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


a_    :  Optional[int]						  =		logging.get_logger(__name__)

# General docstring
a_    :  List[str]						  =		'RegNetConfig'

# Base docstring
a_    :  Union[str, Any]						  =		'facebook/regnet-y-040'
a_    :  Optional[Any]						  =		[1, 1_0_8_8, 7, 7]

# Image classification docstring
a_    :  Dict						  =		'facebook/regnet-y-040'
a_    :  List[Any]						  =		'tabby, tabby cat'

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





class  lowerCamelCase__	(    nn.Module):
     """simple docstring"""



     def __init__(self					,      __a					,      __a					,      __a = 3					,      __a = 1					,      __a = 1					,      __a = "relu"					,      ):






           '''simple docstring'''



           super().__init__()
           lowerCamelCase             =		nn.Convad(
               __a					,      __a					,      kernel_size=__a					,      stride=__a					,      padding=kernel_size // 2					,      groups=__a					,      bias=__a					,      )
           lowerCamelCase             =		nn.BatchNormad(__a     )
           lowerCamelCase             =		ACTaFN[activation] if activation is not None else nn.Identity()







     def     _a   (self					,      __a     ):






           '''simple docstring'''



           lowerCamelCase             =		self.convolution(__a     )
           lowerCamelCase             =		self.normalization(__a     )
           lowerCamelCase             =		self.activation(__a     )
           return hidden_state





class  lowerCamelCase__	(    nn.Module):
     """simple docstring"""



     def __init__(self					,      __a     ):






           '''simple docstring'''



           super().__init__()
           lowerCamelCase             =		RegNetConvLayer(
               config.num_channels					,      config.embedding_size					,      kernel_size=3					,      stride=2					,      activation=config.hidden_act     )
           lowerCamelCase             =		config.num_channels







     def     _a   (self					,      __a     ):






           '''simple docstring'''



           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(__a     )
           return hidden_state





class  lowerCamelCase__	(    nn.Module):
     """simple docstring"""



     def __init__(self					,      __a					,      __a					,      __a = 2     ):






           '''simple docstring'''



           super().__init__()
           lowerCamelCase             =		nn.Convad(__a					,      __a					,      kernel_size=1					,      stride=__a					,      bias=__a     )
           lowerCamelCase             =		nn.BatchNormad(__a     )







     def     _a   (self					,      __a     ):






           '''simple docstring'''



           lowerCamelCase             =		self.convolution(__a     )
           lowerCamelCase             =		self.normalization(__a     )
           return hidden_state





class  lowerCamelCase__	(    nn.Module):
     """simple docstring"""



     def __init__(self					,      __a					,      __a     ):






           '''simple docstring'''



           super().__init__()

           lowerCamelCase             =		nn.AdaptiveAvgPoolad((1, 1)     )
           lowerCamelCase             =		nn.Sequential(
               nn.Convad(__a					,      __a					,      kernel_size=1     )					,      nn.ReLU()					,      nn.Convad(__a					,      __a					,      kernel_size=1     )					,      nn.Sigmoid()					,      )







     def     _a   (self					,      __a     ):






           '''simple docstring'''



           lowerCamelCase             =		self.pooler(__a     )
           lowerCamelCase             =		self.attention(__a     )
           lowerCamelCase             =		hidden_state * attention
           return hidden_state





class  lowerCamelCase__	(    nn.Module):
     """simple docstring"""



     def __init__(self					,      __a					,      __a					,      __a					,      __a = 1     ):






           '''simple docstring'''



           super().__init__()
           lowerCamelCase             =		in_channels != out_channels or stride != 1
           lowerCamelCase             =		max(1					,      out_channels // config.groups_width     )
           lowerCamelCase             =		(
               RegNetShortCut(__a					,      __a					,      stride=__a     ) if should_apply_shortcut else nn.Identity()
           )
           lowerCamelCase             =		nn.Sequential(
               RegNetConvLayer(__a					,      __a					,      kernel_size=1					,      activation=config.hidden_act     )					,      RegNetConvLayer(__a					,      __a					,      stride=__a					,      groups=__a					,      activation=config.hidden_act     )					,      RegNetConvLayer(__a					,      __a					,      kernel_size=1					,      activation=__a     )					,      )
           lowerCamelCase             =		ACTaFN[config.hidden_act]







     def     _a   (self					,      __a     ):






           '''simple docstring'''



           lowerCamelCase             =		hidden_state
           lowerCamelCase             =		self.layer(__a     )
           lowerCamelCase             =		self.shortcut(__a     )
           hidden_state += residual
           lowerCamelCase             =		self.activation(__a     )
           return hidden_state





class  lowerCamelCase__	(    nn.Module):
     """simple docstring"""



     def __init__(self					,      __a					,      __a					,      __a					,      __a = 1     ):






           '''simple docstring'''



           super().__init__()
           lowerCamelCase             =		in_channels != out_channels or stride != 1
           lowerCamelCase             =		max(1					,      out_channels // config.groups_width     )
           lowerCamelCase             =		(
               RegNetShortCut(__a					,      __a					,      stride=__a     ) if should_apply_shortcut else nn.Identity()
           )
           lowerCamelCase             =		nn.Sequential(
               RegNetConvLayer(__a					,      __a					,      kernel_size=1					,      activation=config.hidden_act     )					,      RegNetConvLayer(__a					,      __a					,      stride=__a					,      groups=__a					,      activation=config.hidden_act     )					,      RegNetSELayer(__a					,      reduced_channels=int(round(in_channels / 4     )     )     )					,      RegNetConvLayer(__a					,      __a					,      kernel_size=1					,      activation=__a     )					,      )
           lowerCamelCase             =		ACTaFN[config.hidden_act]







     def     _a   (self					,      __a     ):






           '''simple docstring'''



           lowerCamelCase             =		hidden_state
           lowerCamelCase             =		self.layer(__a     )
           lowerCamelCase             =		self.shortcut(__a     )
           hidden_state += residual
           lowerCamelCase             =		self.activation(__a     )
           return hidden_state





class  lowerCamelCase__	(    nn.Module):
     """simple docstring"""



     def __init__(self					,      __a					,      __a					,      __a					,      __a = 2					,      __a = 2					,      ):






           '''simple docstring'''



           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(
                   __a					,      __a					,      __a					,      stride=__a					,      )					,      *[layer(__a					,      __a					,      __a     ) for _ in range(depth - 1     )]					,      )







     def     _a   (self					,      __a     ):






           '''simple docstring'''



           lowerCamelCase             =		self.layers(__a     )
           return hidden_state





class  lowerCamelCase__	(    nn.Module):
     """simple docstring"""



     def __init__(self					,      __a     ):






           '''simple docstring'''



           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(
                   __a					,      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(__a					,      config.depths[1:]     ):
                 self.stages.append(RegNetStage(__a					,      __a					,      __a					,      depth=__a     )     )







     def     _a   (self					,      __a					,      __a = False					,      __a = True     ):






           '''simple docstring'''



           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(__a     )

           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=__a					,      hidden_states=__a     )





class  lowerCamelCase__	(    UpperCAmelCase_):
     """simple docstring"""



     _A      =      RegNetConfig
     _A      =      'regnet'
     _A      =      'pixel_values'
     _A      =      True







     def     _a   (self					,      __a     ):






           '''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     _a   (self					,      __a					,      __a=False     ):






           '''simple docstring'''



           if isinstance(__a					,      __a     ):
                 lowerCamelCase             =		value



a_    :  Dict						  =		R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

a_    :  Optional[Any]						  =		R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n'





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



     def __init__(self					,      __a     ):






           '''simple docstring'''



           super().__init__(__a     )
           lowerCamelCase             =		config
           lowerCamelCase             =		RegNetEmbeddings(__a     )
           lowerCamelCase             =		RegNetEncoder(__a     )
           lowerCamelCase             =		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     _a   (self					,      __a					,      __a = None					,      __a = None     ):






           '''simple docstring'''



           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(__a     )

           lowerCamelCase             =		self.encoder(
               __a					,      output_hidden_states=__a					,      return_dict=__a     )

           lowerCamelCase             =		encoder_outputs[0]

           lowerCamelCase             =		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    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '							,     UpperCAmelCase_							,     )
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class  lowerCamelCase__	(    UpperCAmelCase_):
     """simple docstring"""



     def __init__(self					,      __a     ):






           '''simple docstring'''



           super().__init__(__a     )
           lowerCamelCase             =		config.num_labels
           lowerCamelCase             =		RegNetModel(__a     )
           # 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(__a     )
     @add_code_sample_docstrings(
         checkpoint=_IMAGE_CLASS_CHECKPOINT					,      output_type=__a					,      config_class=_CONFIG_FOR_DOC					,      expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT					,      )
     def     _a   (self					,      __a = None					,      __a = None					,      __a = None					,      __a = None					,      ):






           '''simple docstring'''



           lowerCamelCase             =		return_dict if return_dict is not None else self.config.use_return_dict

           lowerCamelCase             =		self.regnet(__a					,      output_hidden_states=__a					,      return_dict=__a     )

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

           lowerCamelCase             =		self.classifier(__a     )

           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(__a					,      __a     )
                 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(__a					,      __a     )

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

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