
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


lowerCamelCase_    :			str    =	{
    """configuration_xlm_roberta""": [
        """XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """XLMRobertaConfig""",
        """XLMRobertaOnnxConfig""",
    ],
}

try:
							if not is_sentencepiece_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCamelCase_    :			Tuple    =	["""XLMRobertaTokenizer"""]

try:
							if not is_tokenizers_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCamelCase_    :			int    =	["""XLMRobertaTokenizerFast"""]

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCamelCase_    :			Optional[int]    =	[
							    """XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """XLMRobertaForCausalLM""",
							    """XLMRobertaForMaskedLM""",
							    """XLMRobertaForMultipleChoice""",
							    """XLMRobertaForQuestionAnswering""",
							    """XLMRobertaForSequenceClassification""",
							    """XLMRobertaForTokenClassification""",
							    """XLMRobertaModel""",
							    """XLMRobertaPreTrainedModel""",
							]

try:
							if not is_tf_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCamelCase_    :			List[str]    =	[
							    """TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """TFXLMRobertaForCausalLM""",
							    """TFXLMRobertaForMaskedLM""",
							    """TFXLMRobertaForMultipleChoice""",
							    """TFXLMRobertaForQuestionAnswering""",
							    """TFXLMRobertaForSequenceClassification""",
							    """TFXLMRobertaForTokenClassification""",
							    """TFXLMRobertaModel""",
							    """TFXLMRobertaPreTrainedModel""",
							]

try:
							if not is_flax_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCamelCase_    :			Dict    =	[
							    """FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """FlaxXLMRobertaForMaskedLM""",
							    """FlaxXLMRobertaForCausalLM""",
							    """FlaxXLMRobertaForMultipleChoice""",
							    """FlaxXLMRobertaForQuestionAnswering""",
							    """FlaxXLMRobertaForSequenceClassification""",
							    """FlaxXLMRobertaForTokenClassification""",
							    """FlaxXLMRobertaModel""",
							    """FlaxXLMRobertaPreTrainedModel""",
							]

if TYPE_CHECKING:
							from .configuration_xlm_roberta import (
							    XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
							    XLMRobertaConfig,
							    XLMRobertaOnnxConfig,
							)

							try:
														if not is_sentencepiece_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_xlm_roberta import XLMRobertaTokenizer

							try:
														if not is_tokenizers_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_xlm_roberta import (
														    XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
														    XLMRobertaForCausalLM,
														    XLMRobertaForMaskedLM,
														    XLMRobertaForMultipleChoice,
														    XLMRobertaForQuestionAnswering,
														    XLMRobertaForSequenceClassification,
														    XLMRobertaForTokenClassification,
														    XLMRobertaModel,
														    XLMRobertaPreTrainedModel,
														)

							try:
														if not is_tf_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_tf_xlm_roberta import (
														    TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
														    TFXLMRobertaForCausalLM,
														    TFXLMRobertaForMaskedLM,
														    TFXLMRobertaForMultipleChoice,
														    TFXLMRobertaForQuestionAnswering,
														    TFXLMRobertaForSequenceClassification,
														    TFXLMRobertaForTokenClassification,
														    TFXLMRobertaModel,
														    TFXLMRobertaPreTrainedModel,
														)

							try:
														if not is_flax_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_flax_xlm_roberta import (
														    FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
														    FlaxXLMRobertaForCausalLM,
														    FlaxXLMRobertaForMaskedLM,
														    FlaxXLMRobertaForMultipleChoice,
														    FlaxXLMRobertaForQuestionAnswering,
														    FlaxXLMRobertaForSequenceClassification,
														    FlaxXLMRobertaForTokenClassification,
														    FlaxXLMRobertaModel,
														    FlaxXLMRobertaPreTrainedModel,
														)

else:
							import sys

							lowerCamelCase_    :			str    =	_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)








from typing import List, Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ... import AutoBackbone
from ...modeling_outputs import SemanticSegmenterOutput
from ...modeling_utils import PreTrainedModel
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
from ...utils.backbone_utils import BackboneMixin
from .configuration_upernet import UperNetConfig


lowerCamelCase_    :			List[Any]    =	[
    """openmmlab/upernet-convnext-tiny""",
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
lowerCamelCase_    :			int    =	"""UperNetConfig"""

class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							str    ,						snake_case_			:							int    ,						snake_case_			:							int    ,						snake_case_			:							Union[int, Tuple[int, int]]    ,						snake_case_			:							Union[int, Tuple[int, int], str] = 0    ,						snake_case_			:							bool = False    ,						snake_case_			:							Union[int, Tuple[int, int]] = 1    ,						):
							super().__init__()
							UpperCamelCase_:				Union[str, Any]						=    nn.Convad(
							    in_channels=snake_case_    ,						out_channels=snake_case_    ,						kernel_size=snake_case_    ,						padding=snake_case_    ,						bias=snake_case_    ,						dilation=snake_case_    ,						)
							UpperCamelCase_:				Any						=    nn.BatchNormad(snake_case_   )
							UpperCamelCase_:				int						=    nn.ReLU()




			def    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							torch.Tensor   ):
							UpperCamelCase_:				str						=    self.conv(snake_case_   )
							UpperCamelCase_:				str						=    self.batch_norm(snake_case_   )
							UpperCamelCase_:				Any						=    self.activation(snake_case_   )

							return output




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Optional[int]    ,						snake_case_			:							int    ,						snake_case_			:							int    ,						snake_case_			:							int   ):
							super().__init__()
							UpperCamelCase_:				Any						=    [
							    nn.AdaptiveAvgPoolad(snake_case_   ),
							    UperNetConvModule(snake_case_    ,						snake_case_    ,						kernel_size=1   ),
							]
							for i, layer in enumerate(self.layers   ):
											self.add_module(str(snake_case_   )    ,						snake_case_   )




			def    lowerCAmelCase__						(							self			:							Dict    ,						snake_case_			:							torch.Tensor   ):
							UpperCamelCase_:				str						=    input
							for layer in self.layers:
											UpperCamelCase_:				int						=    layer(snake_case_   )
							return hidden_state




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							List[Any]    ,						snake_case_			:							Tuple[int, ...]    ,						snake_case_			:							int    ,						snake_case_			:							int    ,						snake_case_			:							bool   ):
							super().__init__()
							UpperCamelCase_:				Any						=    pool_scales
							UpperCamelCase_:				List[str]						=    align_corners
							UpperCamelCase_:				Dict						=    in_channels
							UpperCamelCase_:				int						=    channels
							UpperCamelCase_:				Union[str, Any]						=    []
							for i, pool_scale in enumerate(snake_case_   ):
											UpperCamelCase_:				Dict						=    UperNetPyramidPoolingBlock(pool_scale=snake_case_    ,						in_channels=snake_case_    ,						channels=snake_case_   )
											self.blocks.append(snake_case_   )
											self.add_module(str(snake_case_   )    ,						snake_case_   )




			def    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							torch.Tensor   ):
							UpperCamelCase_:				Optional[int]						=    []
							for ppm in self.blocks:
											UpperCamelCase_:				int						=    ppm(snake_case_   )
											UpperCamelCase_:				Optional[int]						=    nn.functional.interpolate(
											    snake_case_    ,						size=x.size()[2:]    ,						mode="""bilinear"""    ,						align_corners=self.align_corners   )
											ppm_outs.append(snake_case_   )
							return ppm_outs




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							int    ,						snake_case_			:							Tuple    ,						snake_case_			:							Any   ):
							super().__init__()

							UpperCamelCase_:				Tuple						=    config
							UpperCamelCase_:				Dict						=    config.pool_scales  # e.g. (1, 2, 3, 6)
							UpperCamelCase_:				Tuple						=    in_channels
							UpperCamelCase_:				Dict						=    config.hidden_size
							UpperCamelCase_:				str						=    False
							UpperCamelCase_:				int						=    nn.Convad(self.channels    ,						config.num_labels    ,						kernel_size=1   )

							# PSP Module
							UpperCamelCase_:				Tuple						=    UperNetPyramidPoolingModule(
							    self.pool_scales    ,						self.in_channels[-1]    ,						self.channels    ,						align_corners=self.align_corners    ,						)
							UpperCamelCase_:				int						=    UperNetConvModule(
							    self.in_channels[-1] + len(self.pool_scales   ) * self.channels    ,						self.channels    ,						kernel_size=3    ,						padding=1    ,						)
							# FPN Module
							UpperCamelCase_:				Union[str, Any]						=    nn.ModuleList()
							UpperCamelCase_:				List[str]						=    nn.ModuleList()
							for in_channels in self.in_channels[:-1]:  # skip the top layer
											UpperCamelCase_:				Union[str, Any]						=    UperNetConvModule(snake_case_    ,						self.channels    ,						kernel_size=1   )
											UpperCamelCase_:				List[str]						=    UperNetConvModule(self.channels    ,						self.channels    ,						kernel_size=3    ,						padding=1   )
											self.lateral_convs.append(snake_case_   )
											self.fpn_convs.append(snake_case_   )

							UpperCamelCase_:				Tuple						=    UperNetConvModule(
							    len(self.in_channels   ) * self.channels    ,						self.channels    ,						kernel_size=3    ,						padding=1    ,						)

			def    lowerCAmelCase__						(							self			:							List[str]   ):
							self.apply(self._init_weights   )

			def    lowerCAmelCase__						(							self			:							List[str]    ,						snake_case_			:							Union[str, Any]   ):
							if isinstance(snake_case_    ,						nn.Convad   ):
											module.weight.data.normal_(mean=0.0    ,						std=self.config.initializer_range   )
											if module.bias is not None:
															module.bias.data.zero_()

			def    lowerCAmelCase__						(							self			:							List[Any]    ,						snake_case_			:							Optional[int]   ):
							UpperCamelCase_:				Tuple						=    inputs[-1]
							UpperCamelCase_:				str						=    [x]
							psp_outs.extend(self.psp_modules(snake_case_   )   )
							UpperCamelCase_:				Union[str, Any]						=    torch.cat(snake_case_    ,						dim=1   )
							UpperCamelCase_:				int						=    self.bottleneck(snake_case_   )

							return output




			def    lowerCAmelCase__						(							self			:							str    ,						snake_case_			:							torch.Tensor   ):
							# build laterals
							UpperCamelCase_:				Union[str, Any]						=    [lateral_conv(encoder_hidden_states[i]   ) for i, lateral_conv in enumerate(self.lateral_convs   )]

							laterals.append(self.psp_forward(snake_case_   )   )

							# build top-down path
							UpperCamelCase_:				List[Any]						=    len(snake_case_   )
							for i in range(used_backbone_levels - 1    ,						0    ,						-1   ):
											UpperCamelCase_:				Union[str, Any]						=    laterals[i - 1].shape[2:]
											UpperCamelCase_:				Union[str, Any]						=    laterals[i - 1] + nn.functional.interpolate(
											    laterals[i]    ,						size=snake_case_    ,						mode="""bilinear"""    ,						align_corners=self.align_corners   )

							# build outputs
							UpperCamelCase_:				Optional[int]						=    [self.fpn_convs[i](laterals[i]   ) for i in range(used_backbone_levels - 1   )]
							# append psp feature
							fpn_outs.append(laterals[-1]   )

							for i in range(used_backbone_levels - 1    ,						0    ,						-1   ):
											UpperCamelCase_:				Any						=    nn.functional.interpolate(
											    fpn_outs[i]    ,						size=fpn_outs[0].shape[2:]    ,						mode="""bilinear"""    ,						align_corners=self.align_corners   )
							UpperCamelCase_:				Any						=    torch.cat(snake_case_    ,						dim=1   )
							UpperCamelCase_:				Any						=    self.fpn_bottleneck(snake_case_   )
							UpperCamelCase_:				Optional[int]						=    self.classifier(snake_case_   )

							return output




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Optional[int]    ,						snake_case_			:							List[str]    ,						snake_case_			:							int = 2    ,						snake_case_			:							int = 3    ,						snake_case_			:							Union[int, Tuple[int, int]] = 1   ):
							super().__init__()

							UpperCamelCase_:				Optional[int]						=    config
							UpperCamelCase_:				List[str]						=    config.auxiliary_in_channels
							UpperCamelCase_:				Tuple						=    config.auxiliary_channels
							UpperCamelCase_:				Dict						=    config.auxiliary_num_convs
							UpperCamelCase_:				Tuple						=    config.auxiliary_concat_input
							UpperCamelCase_:				int						=    in_index

							UpperCamelCase_:				Dict						=    (kernel_size // 2) * dilation
							UpperCamelCase_:				int						=    []
							convs.append(
							    UperNetConvModule(
							        self.in_channels    ,						self.channels    ,						kernel_size=snake_case_    ,						padding=snake_case_    ,						dilation=snake_case_   )   )
							for i in range(self.num_convs - 1   ):
											convs.append(
											    UperNetConvModule(
											        self.channels    ,						self.channels    ,						kernel_size=snake_case_    ,						padding=snake_case_    ,						dilation=snake_case_   )   )
							if self.num_convs == 0:
											UpperCamelCase_:				List[str]						=    nn.Identity()
							else:
											UpperCamelCase_:				List[str]						=    nn.Sequential(*snake_case_   )
							if self.concat_input:
											UpperCamelCase_:				Tuple						=    UperNetConvModule(
											    self.in_channels + self.channels    ,						self.channels    ,						kernel_size=snake_case_    ,						padding=kernel_size // 2   )

							UpperCamelCase_:				str						=    nn.Convad(self.channels    ,						config.num_labels    ,						kernel_size=1   )

			def    lowerCAmelCase__						(							self			:							Any   ):
							self.apply(self._init_weights   )

			def    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							Union[str, Any]   ):
							if isinstance(snake_case_    ,						nn.Convad   ):
											module.weight.data.normal_(mean=0.0    ,						std=self.config.initializer_range   )
											if module.bias is not None:
															module.bias.data.zero_()




			def    lowerCAmelCase__						(							self			:							str    ,						snake_case_			:							torch.Tensor   ):
							# just take the relevant feature maps
							UpperCamelCase_:				Tuple						=    encoder_hidden_states[self.in_index]
							UpperCamelCase_:				Optional[int]						=    self.convs(snake_case_   )
							if self.concat_input:
											UpperCamelCase_:				Optional[int]						=    self.conv_cat(torch.cat([hidden_states, output]    ,						dim=1   )   )
							UpperCamelCase_:				Optional[Any]						=    self.classifier(snake_case_   )
							return output




class 							_UpperCamelCase					(       _A	):






			'''simple docstring'''

			__UpperCamelCase   :    List[Any]          =			UperNetConfig
			__UpperCamelCase   :    Union[str, Any]          =			"""pixel_values"""
			__UpperCamelCase   :    Dict          =			True

			def    lowerCAmelCase__						(							self			:							Optional[int]    ,						snake_case_			:							str   ):
							if isinstance(snake_case_    ,						snake_case_   ):
											module.backbone.init_weights()
											module.decode_head.init_weights()
											module.auxiliary_head.init_weights()

			def    lowerCAmelCase__						(							self			:							Dict   ):
							self.backbone.init_weights()
							self.decode_head.init_weights()
							self.auxiliary_head.init_weights()




			def    lowerCAmelCase__						(							self			:							str    ,						snake_case_			:							Tuple    ,						snake_case_			:							Tuple=False   ):
							if isinstance(snake_case_    ,						snake_case_   ):
											UpperCamelCase_:				Union[str, Any]						=    value




lowerCamelCase_    :			Dict    =	r"""
    Parameters:
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.
        config ([`UperNetConfig`]): 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_    :			Tuple    =	r"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See
            `attentions` under returned tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers of the backbone. 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(
    """UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes."""  ,							_A  ,							)
class 							_UpperCamelCase					(       _A	):






			'''simple docstring'''

			def __init__(							self			:							int    ,						snake_case_			:							Dict   ):
							super().__init__(snake_case_   )

							UpperCamelCase_:				int						=    AutoBackbone.from_config(config.backbone_config   )

							# Semantic segmentation head(s)
							UpperCamelCase_:				Optional[Any]						=    UperNetHead(snake_case_    ,						in_channels=self.backbone.channels   )
							UpperCamelCase_:				List[str]						=    UperNetFCNHead(snake_case_   ) if config.use_auxiliary_head else None

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




			@add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("""batch_size, sequence_length"""   )   )
			@replace_return_docstrings(output_type=snake_case_    ,						config_class=_CONFIG_FOR_DOC   )
			def    lowerCAmelCase__						(							self			:							Union[str, Any]    ,						snake_case_			:							Optional[torch.Tensor] = None    ,						snake_case_			:							Optional[bool] = None    ,						snake_case_			:							Optional[bool] = None    ,						snake_case_			:							Optional[torch.Tensor] = None    ,						snake_case_			:							Optional[bool] = None    ,						):
							UpperCamelCase_:				Union[str, Any]						=    return_dict if return_dict is not None else self.config.use_return_dict
							UpperCamelCase_:				Union[str, Any]						=    (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							UpperCamelCase_:				int						=    output_attentions if output_attentions is not None else self.config.output_attentions

							UpperCamelCase_:				Dict						=    self.backbone.forward_with_filtered_kwargs(
							    snake_case_    ,						output_hidden_states=snake_case_    ,						output_attentions=snake_case_   )
							UpperCamelCase_:				Any						=    outputs.feature_maps

							UpperCamelCase_:				Dict						=    self.decode_head(snake_case_   )
							UpperCamelCase_:				Optional[Any]						=    nn.functional.interpolate(snake_case_    ,						size=pixel_values.shape[2:]    ,						mode="""bilinear"""    ,						align_corners=snake_case_   )

							UpperCamelCase_:				Dict						=    None
							if self.auxiliary_head is not None:
											UpperCamelCase_:				List[str]						=    self.auxiliary_head(snake_case_   )
											UpperCamelCase_:				Optional[int]						=    nn.functional.interpolate(
											    snake_case_    ,						size=pixel_values.shape[2:]    ,						mode="""bilinear"""    ,						align_corners=snake_case_   )

							UpperCamelCase_:				List[Any]						=    None
							if labels is not None:
											if self.config.num_labels == 1:
															raise ValueError("""The number of labels should be greater than one"""   )
											else:
															# compute weighted loss
															UpperCamelCase_:				List[Any]						=    CrossEntropyLoss(ignore_index=self.config.loss_ignore_index   )
															UpperCamelCase_:				Dict						=    loss_fct(snake_case_    ,						snake_case_   )
															UpperCamelCase_:				Tuple						=    loss_fct(snake_case_    ,						snake_case_   )
															UpperCamelCase_:				List[Any]						=    main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

							if not return_dict:
											if output_hidden_states:
															UpperCamelCase_:				Tuple						=    (logits,) + outputs[1:]
											else:
															UpperCamelCase_:				Union[str, Any]						=    (logits,) + outputs[2:]
											return ((loss,) + output) if loss is not None else output

							return SemanticSegmenterOutput(
							    loss=snake_case_    ,						logits=snake_case_    ,						hidden_states=outputs.hidden_states    ,						attentions=outputs.attentions    ,						)






