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__	   =						[
    'openmmlab/upernet-convnext-tiny',
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
lowerCAmelCase__	   =						'UperNetConfig'
class 					snake_case	(     nn.Module   ):

   """simple docstring"""







   def __init__(    self					,	lowerCAmelCase_					,	lowerCAmelCase_					,	lowerCAmelCase_					,	lowerCAmelCase_ = 0					,	lowerCAmelCase_ = False					,	lowerCAmelCase_ = 1					,	):
     super().__init__()
     __lowercase					=		nn.Convad(
         in_channels=lowerCAmelCase_					,	out_channels=lowerCAmelCase_					,	kernel_size=lowerCAmelCase_					,	padding=lowerCAmelCase_					,	bias=lowerCAmelCase_					,	dilation=lowerCAmelCase_					,	)
     __lowercase					=		nn.BatchNormad(lowerCAmelCase_	)
     __lowercase					=		nn.ReLU()





   def 				snake_case__							(    self					,	lowerCAmelCase_	):
     __lowercase					=		self.conv(lowerCAmelCase_	)
     __lowercase					=		self.batch_norm(lowerCAmelCase_	)
     __lowercase					=		self.activation(lowerCAmelCase_	)

     return output







class 					snake_case	(     nn.Module   ):

   """simple docstring"""







   def __init__(    self					,	lowerCAmelCase_					,	lowerCAmelCase_					,	lowerCAmelCase_	):
     super().__init__()
     __lowercase					=		[
         nn.AdaptiveAvgPoolad(lowerCAmelCase_	),
         UperNetConvModule(lowerCAmelCase_					,	lowerCAmelCase_					,	kernel_size=1	),
     ]
     for i, layer in enumerate(self.layers	):
       self.add_module(str(lowerCAmelCase_	)					,	lowerCAmelCase_	)





   def 				snake_case__							(    self					,	lowerCAmelCase_	):
     __lowercase					=		input
     for layer in self.layers:
       __lowercase					=		layer(lowerCAmelCase_	)
     return hidden_state







class 					snake_case	(     nn.Module   ):

   """simple docstring"""







   def __init__(    self					,	lowerCAmelCase_					,	lowerCAmelCase_					,	lowerCAmelCase_					,	lowerCAmelCase_	):
     super().__init__()
     __lowercase					=		pool_scales
     __lowercase					=		align_corners
     __lowercase					=		in_channels
     __lowercase					=		channels
     __lowercase					=		[]
     for i, pool_scale in enumerate(lowerCAmelCase_	):
       __lowercase					=		UperNetPyramidPoolingBlock(pool_scale=lowerCAmelCase_					,	in_channels=lowerCAmelCase_					,	channels=lowerCAmelCase_	)
       self.blocks.append(lowerCAmelCase_	)
       self.add_module(str(lowerCAmelCase_	)					,	lowerCAmelCase_	)





   def 				snake_case__							(    self					,	lowerCAmelCase_	):
     __lowercase					=		[]
     for ppm in self.blocks:
       __lowercase					=		ppm(lowerCAmelCase_	)
       __lowercase					=		nn.functional.interpolate(
           lowerCAmelCase_					,	size=x.size()[2:]					,	mode="bilinear"					,	align_corners=self.align_corners	)
       ppm_outs.append(lowerCAmelCase_	)
     return ppm_outs







class 					snake_case	(     nn.Module   ):

   """simple docstring"""







   def __init__(    self					,	lowerCAmelCase_					,	lowerCAmelCase_	):
     super().__init__()

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

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

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





   def 				snake_case__							(    self	):
     self.apply(self._init_weights	)





   def 				snake_case__							(    self					,	lowerCAmelCase_	):






     if isinstance(lowerCAmelCase_					,	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 				snake_case__							(    self					,	lowerCAmelCase_	):
     __lowercase					=		inputs[-1]
     __lowercase					=		[x]
     psp_outs.extend(self.psp_modules(lowerCAmelCase_	)	)
     __lowercase					=		torch.cat(lowerCAmelCase_					,	dim=1	)
     __lowercase					=		self.bottleneck(lowerCAmelCase_	)

     return output





   def 				snake_case__							(    self					,	lowerCAmelCase_	):
     __lowercase					=		[lateral_conv(encoder_hidden_states[i]	) for i, lateral_conv in enumerate(self.lateral_convs	)]

     laterals.append(self.psp_forward(lowerCAmelCase_	)	)

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

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

     return output







class 					snake_case	(     nn.Module   ):

   """simple docstring"""







   def __init__(    self					,	lowerCAmelCase_					,	lowerCAmelCase_ = 2					,	lowerCAmelCase_ = 3					,	lowerCAmelCase_ = 1	):
     super().__init__()

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

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

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





   def 				snake_case__							(    self	):
     self.apply(self._init_weights	)





   def 				snake_case__							(    self					,	lowerCAmelCase_	):






     if isinstance(lowerCAmelCase_					,	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 				snake_case__							(    self					,	lowerCAmelCase_	):
     __lowercase					=		encoder_hidden_states[self.in_index]
     __lowercase					=		self.convs(lowerCAmelCase_	)
     if self.concat_input:
       __lowercase					=		self.conv_cat(torch.cat([hidden_states, output]					,	dim=1	)	)
     __lowercase					=		self.classifier(lowerCAmelCase_	)
     return output







class 					snake_case	(     __snake_case   ):

   """simple docstring"""







   __lowerCAmelCase   						=      UperNetConfig
   __lowerCAmelCase   						=      'pixel_values'
   __lowerCAmelCase   						=      True





   def 				snake_case__							(    self					,	lowerCAmelCase_	):






     if isinstance(lowerCAmelCase_					,	lowerCAmelCase_	):
       module.backbone.init_weights()
       module.decode_head.init_weights()
       module.auxiliary_head.init_weights()





   def 				snake_case__							(    self	):
     self.backbone.init_weights()
     self.decode_head.init_weights()
     self.auxiliary_head.init_weights()





   def 				snake_case__							(    self					,	lowerCAmelCase_					,	lowerCAmelCase_=False	):






     if isinstance(lowerCAmelCase_					,	lowerCAmelCase_	):
       __lowercase					=		value







lowerCAmelCase__	   =						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'

lowerCAmelCase__	   =						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."""							,__snake_case							,)
class 					snake_case	(     __snake_case   ):

   """simple docstring"""







   def __init__(    self					,	lowerCAmelCase_	):
     super().__init__(lowerCAmelCase_	)

     __lowercase					=		AutoBackbone.from_config(config.backbone_config	)

     # Semantic segmentation head(s)
     __lowercase					=		UperNetHead(lowerCAmelCase_					,	in_channels=self.backbone.channels	)
     __lowercase					=		UperNetFCNHead(lowerCAmelCase_	) 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=lowerCAmelCase_					,	config_class=_CONFIG_FOR_DOC	)
   def 				snake_case__							(    self					,	lowerCAmelCase_ = None					,	lowerCAmelCase_ = None					,	lowerCAmelCase_ = None					,	lowerCAmelCase_ = None					,	lowerCAmelCase_ = None					,	):
     __lowercase					=		return_dict if return_dict is not None else self.config.use_return_dict
     __lowercase					=		(
         output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
     )
     __lowercase					=		output_attentions if output_attentions is not None else self.config.output_attentions

     __lowercase					=		self.backbone.forward_with_filtered_kwargs(
         lowerCAmelCase_					,	output_hidden_states=lowerCAmelCase_					,	output_attentions=lowerCAmelCase_	)
     __lowercase					=		outputs.feature_maps

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

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

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

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

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





"""simple docstring"""



from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase_							=							logging.get_logger(__name__)

lowercase_							=							{
    's-JoL/Open-Llama-V1': 'https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json',
}







class    __a						( __snake_case							):
				lowerCamelCase     :       Union[str, Any]			       ='open-llama'







				def __init__( self      ,	UpperCAmelCase=10_0000      ,	UpperCAmelCase=4096      ,	UpperCAmelCase=1_1008      ,	UpperCAmelCase=32      ,	UpperCAmelCase=32      ,	UpperCAmelCase="silu"      ,	UpperCAmelCase=2048      ,	UpperCAmelCase=0.0_2      ,	UpperCAmelCase=1E-6      ,	UpperCAmelCase=True      ,	UpperCAmelCase=0      ,	UpperCAmelCase=1      ,	UpperCAmelCase=2      ,	UpperCAmelCase=False      ,	UpperCAmelCase=True      ,	UpperCAmelCase=0.1      ,	UpperCAmelCase=0.1      ,	UpperCAmelCase=True      ,	UpperCAmelCase=True      ,	UpperCAmelCase=None      ,	**UpperCAmelCase      ,	):

					'''simple docstring'''






					lowerCAmelCase_      							=			vocab_size
					lowerCAmelCase_      							=			max_position_embeddings
					lowerCAmelCase_      							=			hidden_size
					lowerCAmelCase_      							=			intermediate_size
					lowerCAmelCase_      							=			num_hidden_layers
					lowerCAmelCase_      							=			num_attention_heads
					lowerCAmelCase_      							=			hidden_act
					lowerCAmelCase_      							=			initializer_range
					lowerCAmelCase_      							=			rms_norm_eps
					lowerCAmelCase_      							=			use_cache
					lowerCAmelCase_      							=			kwargs.pop(
					    '''use_memorry_efficient_attention'''      ,	UpperCAmelCase   )
					lowerCAmelCase_      							=			hidden_dropout_prob
					lowerCAmelCase_      							=			attention_dropout_prob
					lowerCAmelCase_      							=			use_stable_embedding
					lowerCAmelCase_      							=			shared_input_output_embedding
					lowerCAmelCase_      							=			rope_scaling
					self._rope_scaling_validation()

					super().__init__(
					    pad_token_id=UpperCAmelCase      ,	bos_token_id=UpperCAmelCase      ,	eos_token_id=UpperCAmelCase      ,	tie_word_embeddings=UpperCAmelCase      ,	**UpperCAmelCase      ,	)







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					if self.rope_scaling is None:
						return

					if not isinstance(self.rope_scaling      ,	UpperCAmelCase   ) or len(self.rope_scaling   ) != 2:
						raise ValueError(
						    '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '''
						    F"""got {self.rope_scaling}"""   )
					lowerCAmelCase_      							=			self.rope_scaling.get('''type'''      ,	UpperCAmelCase   )
					lowerCAmelCase_      							=			self.rope_scaling.get('''factor'''      ,	UpperCAmelCase   )
					if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
						raise ValueError(
						    F"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"""   )
					if rope_scaling_factor is None or not isinstance(UpperCAmelCase      ,	UpperCAmelCase   ) or rope_scaling_factor <= 1.0:
						raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}"""   )