





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


UpperCamelCase_												=	[
    'openmmlab/upernet-convnext-tiny',
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
UpperCamelCase_												=	'UperNetConfig'

class     snake_case_		(   nn.Module							):






 '''simple docstring'''





 def __init__(  self,		A_,		A_,		A_,		A_ = 0,		A_ = False,		A_ = 1,		)	->       None:
    super().__init__()
    UpperCAmelCase__						=nn.Convad(
        in_channels=A_,		out_channels=A_,		kernel_size=A_,		padding=A_,		bias=A_,		dilation=A_,		)
    UpperCAmelCase__						=nn.BatchNormad(A_		)
    UpperCAmelCase__						=nn.ReLU()






 def  __UpperCAmelCase						(  self,		A_		)	->       torch.Tensor:
    UpperCAmelCase__						=self.conv(A_		)
    UpperCAmelCase__						=self.batch_norm(A_		)
    UpperCAmelCase__						=self.activation(A_		)

    return output

class     snake_case_		(   nn.Module							):






 '''simple docstring'''





 def __init__(  self,		A_,		A_,		A_		)	->       None:
    super().__init__()
    UpperCAmelCase__						=[
        nn.AdaptiveAvgPoolad(A_		),
        UperNetConvModule(A_,		A_,		kernel_size=1		),
    ]
    for i, layer in enumerate(self.layers		):
       self.add_module(str(A_		),		A_		)






 def  __UpperCAmelCase						(  self,		A_		)	->       torch.Tensor:
    UpperCAmelCase__						=input
    for layer in self.layers:
       UpperCAmelCase__						=layer(A_		)
    return hidden_state

class     snake_case_		(   nn.Module							):






 '''simple docstring'''





 def __init__(  self,		A_,		A_,		A_,		A_		)	->       None:
    super().__init__()
    UpperCAmelCase__						=pool_scales
    UpperCAmelCase__						=align_corners
    UpperCAmelCase__						=in_channels
    UpperCAmelCase__						=channels
    UpperCAmelCase__						=[]
    for i, pool_scale in enumerate(A_		):
       UpperCAmelCase__						=UperNetPyramidPoolingBlock(pool_scale=A_,		in_channels=A_,		channels=A_		)
       self.blocks.append(A_		)
       self.add_module(str(A_		),		A_		)






 def  __UpperCAmelCase						(  self,		A_		)	->       List[torch.Tensor]:
    UpperCAmelCase__						=[]
    for ppm in self.blocks:
       UpperCAmelCase__						=ppm(A_		)
       UpperCAmelCase__						=nn.functional.interpolate(
           A_,		size=x.size()[2:],		mode="bilinear",		align_corners=self.align_corners		)
       ppm_outs.append(A_		)
    return ppm_outs

class     snake_case_		(   nn.Module							):






 '''simple docstring'''





 def __init__(  self,		A_,		A_		)	->       Dict:
    super().__init__()

    UpperCAmelCase__						=config
    UpperCAmelCase__						=config.pool_scales  # e.g. (1, 2, 3, 6)
    UpperCAmelCase__						=in_channels
    UpperCAmelCase__						=config.hidden_size
    UpperCAmelCase__						=False
    UpperCAmelCase__						=nn.Convad(self.channels,		config.num_labels,		kernel_size=1		)

    # PSP Module
    UpperCAmelCase__						=UperNetPyramidPoolingModule(
        self.pool_scales,		self.in_channels[-1],		self.channels,		align_corners=self.align_corners,		)
    UpperCAmelCase__						=UperNetConvModule(
        self.in_channels[-1] + len(self.pool_scales		) * self.channels,		self.channels,		kernel_size=3,		padding=1,		)
    # FPN Module
    UpperCAmelCase__						=nn.ModuleList()
    UpperCAmelCase__						=nn.ModuleList()
    for in_channels in self.in_channels[:-1]:  # skip the top layer
       UpperCAmelCase__						=UperNetConvModule(A_,		self.channels,		kernel_size=1		)
       UpperCAmelCase__						=UperNetConvModule(self.channels,		self.channels,		kernel_size=3,		padding=1		)
       self.lateral_convs.append(A_		)
       self.fpn_convs.append(A_		)

    UpperCAmelCase__						=UperNetConvModule(
        len(self.in_channels		) * self.channels,		self.channels,		kernel_size=3,		padding=1,		)

 def  __UpperCAmelCase						(  self		)	->       Optional[int]:
    self.apply(self._init_weights		)

 def  __UpperCAmelCase						(  self,		A_		)	->       Optional[int]:
    if isinstance(A_,		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  __UpperCAmelCase						(  self,		A_		)	->       Union[str, Any]:
    UpperCAmelCase__						=inputs[-1]
    UpperCAmelCase__						=[x]
    psp_outs.extend(self.psp_modules(A_		)		)
    UpperCAmelCase__						=torch.cat(A_,		dim=1		)
    UpperCAmelCase__						=self.bottleneck(A_		)

    return output






 def  __UpperCAmelCase						(  self,		A_		)	->       torch.Tensor:
    # build laterals
    UpperCAmelCase__						=[lateral_conv(encoder_hidden_states[i]		) for i, lateral_conv in enumerate(self.lateral_convs		)]

    laterals.append(self.psp_forward(A_		)		)

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

    # build outputs
    UpperCAmelCase__						=[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__						=nn.functional.interpolate(
           fpn_outs[i],		size=fpn_outs[0].shape[2:],		mode="bilinear",		align_corners=self.align_corners		)
    UpperCAmelCase__						=torch.cat(A_,		dim=1		)
    UpperCAmelCase__						=self.fpn_bottleneck(A_		)
    UpperCAmelCase__						=self.classifier(A_		)

    return output

class     snake_case_		(   nn.Module							):






 '''simple docstring'''





 def __init__(  self,		A_,		A_ = 2,		A_ = 3,		A_ = 1		)	->       None:
    super().__init__()

    UpperCAmelCase__						=config
    UpperCAmelCase__						=config.auxiliary_in_channels
    UpperCAmelCase__						=config.auxiliary_channels
    UpperCAmelCase__						=config.auxiliary_num_convs
    UpperCAmelCase__						=config.auxiliary_concat_input
    UpperCAmelCase__						=in_index

    UpperCAmelCase__						=(kernel_size // 2) * dilation
    UpperCAmelCase__						=[]
    convs.append(
        UperNetConvModule(
            self.in_channels,		self.channels,		kernel_size=A_,		padding=A_,		dilation=A_		)		)
    for i in range(self.num_convs - 1		):
       convs.append(
           UperNetConvModule(
               self.channels,		self.channels,		kernel_size=A_,		padding=A_,		dilation=A_		)		)
    if self.num_convs == 0:
       UpperCAmelCase__						=nn.Identity()
    else:
       UpperCAmelCase__						=nn.Sequential(*A_		)
    if self.concat_input:
       UpperCAmelCase__						=UperNetConvModule(
           self.in_channels + self.channels,		self.channels,		kernel_size=A_,		padding=kernel_size // 2		)

    UpperCAmelCase__						=nn.Convad(self.channels,		config.num_labels,		kernel_size=1		)

 def  __UpperCAmelCase						(  self		)	->       Dict:
    self.apply(self._init_weights		)

 def  __UpperCAmelCase						(  self,		A_		)	->       Optional[Any]:
    if isinstance(A_,		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  __UpperCAmelCase						(  self,		A_		)	->       torch.Tensor:
    # just take the relevant feature maps
    UpperCAmelCase__						=encoder_hidden_states[self.in_index]
    UpperCAmelCase__						=self.convs(A_		)
    if self.concat_input:
       UpperCAmelCase__						=self.conv_cat(torch.cat([hidden_states, output],		dim=1		)		)
    UpperCAmelCase__						=self.classifier(A_		)
    return output

class     snake_case_		(   a							):






 '''simple docstring'''





 __UpperCamelCase       =      UperNetConfig
 __UpperCamelCase       =      'pixel_values'
 __UpperCamelCase       =      True

 def  __UpperCAmelCase						(  self,		A_		)	->       Union[str, Any]:
    if isinstance(A_,		A_		):
       module.backbone.init_weights()
       module.decode_head.init_weights()
       module.auxiliary_head.init_weights()

 def  __UpperCAmelCase						(  self		)	->       int:
    self.backbone.init_weights()
    self.decode_head.init_weights()
    self.auxiliary_head.init_weights()






 def  __UpperCAmelCase						(  self,		A_,		A_=False		)	->       Any:
    if isinstance(A_,		A_		):
       UpperCAmelCase__						=value

UpperCamelCase_												=	R'\n    Parameters:\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n        config ([`UperNetConfig`]): 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'

UpperCamelCase_												=	R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n            `attentions` under returned tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n            returned tensors for more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'

@add_start_docstrings(
    'UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.',		a,		)
class     snake_case_		(   a							):






 '''simple docstring'''





 def __init__(  self,		A_		)	->       Dict:
    super().__init__(A_		)

    UpperCAmelCase__						=AutoBackbone.from_config(config.backbone_config		)

    # Semantic segmentation head(s)
    UpperCAmelCase__						=UperNetHead(A_,		in_channels=self.backbone.channels		)
    UpperCAmelCase__						=UperNetFCNHead(A_		) 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=A_,		config_class=_CONFIG_FOR_DOC		)
 def  __UpperCAmelCase						(  self,		A_ = None,		A_ = None,		A_ = None,		A_ = None,		A_ = None,		)	->       Union[tuple, SemanticSegmenterOutput]:
    UpperCAmelCase__						=return_dict if return_dict is not None else self.config.use_return_dict
    UpperCAmelCase__						=(
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    UpperCAmelCase__						=output_attentions if output_attentions is not None else self.config.output_attentions

    UpperCAmelCase__						=self.backbone.forward_with_filtered_kwargs(
        A_,		output_hidden_states=A_,		output_attentions=A_		)
    UpperCAmelCase__						=outputs.feature_maps

    UpperCAmelCase__						=self.decode_head(A_		)
    UpperCAmelCase__						=nn.functional.interpolate(A_,		size=pixel_values.shape[2:],		mode="bilinear",		align_corners=A_		)

    UpperCAmelCase__						=None
    if self.auxiliary_head is not None:
       UpperCAmelCase__						=self.auxiliary_head(A_		)
       UpperCAmelCase__						=nn.functional.interpolate(
           A_,		size=pixel_values.shape[2:],		mode="bilinear",		align_corners=A_		)

    UpperCAmelCase__						=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__						=CrossEntropyLoss(ignore_index=self.config.loss_ignore_index		)
          UpperCAmelCase__						=loss_fct(A_,		A_		)
          UpperCAmelCase__						=loss_fct(A_,		A_		)
          UpperCAmelCase__						=main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

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

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










from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


UpperCamelCase_												=	logging.get_logger(__name__)

UpperCamelCase_												=	{
    'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json',
    'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json',
    'junnyu/roformer_chinese_char_small': (
        'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json'
    ),
    'junnyu/roformer_chinese_char_base': (
        'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json'
    ),
    'junnyu/roformer_small_discriminator': (
        'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json'
    ),
    'junnyu/roformer_small_generator': (
        'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json'
    ),
    # See all RoFormer models at https://huggingface.co/models?filter=roformer
}

class     snake_case_		(   a							):






 '''simple docstring'''





 __UpperCamelCase       =      'roformer'

 def __init__(  self,		A_=5_0000,		A_=None,		A_=768,		A_=12,		A_=12,		A_=3072,		A_="gelu",		A_=0.1,		A_=0.1,		A_=1536,		A_=2,		A_=0.02,		A_=1E-12,		A_=0,		A_=False,		A_=True,		**A_,		)	->       Dict:
    super().__init__(pad_token_id=A_,		**A_		)

    UpperCAmelCase__						=vocab_size
    UpperCAmelCase__						=hidden_size if embedding_size is None else embedding_size
    UpperCAmelCase__						=hidden_size
    UpperCAmelCase__						=num_hidden_layers
    UpperCAmelCase__						=num_attention_heads
    UpperCAmelCase__						=hidden_act
    UpperCAmelCase__						=intermediate_size
    UpperCAmelCase__						=hidden_dropout_prob
    UpperCAmelCase__						=attention_probs_dropout_prob
    UpperCAmelCase__						=max_position_embeddings
    UpperCAmelCase__						=type_vocab_size
    UpperCAmelCase__						=initializer_range
    UpperCAmelCase__						=layer_norm_eps
    UpperCAmelCase__						=rotary_value
    UpperCAmelCase__						=use_cache

class     snake_case_		(   a							):






 '''simple docstring'''





 @property
 def  __UpperCAmelCase						(  self		)	->       Mapping[str, Mapping[int, str]]:
    if self.task == "multiple-choice":
       UpperCAmelCase__						={0: "batch", 1: "choice", 2: "sequence"}
    else:
       UpperCAmelCase__						={0: "batch", 1: "sequence"}
    UpperCAmelCase__						={0: "batch", 1: "sequence"}
    return OrderedDict(
        [
            ("input_ids", dynamic_axis),
            ("attention_mask", dynamic_axis),
            ("token_type_ids", dynamic_axis),
        ]		)



