



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     __lowerCAmelCase					(    nn.Module		):



			def __init__(		self     :						List[str]				,	A     :						int				,	A     :						int				,	A     :						Union[int, Tuple[int, int]]				,	A     :						Union[int, Tuple[int, int], str] = 0				,	A     :						bool = False				,	A     :						Union[int, Tuple[int, int]] = 1				,	)     ->					None:



						"""simple docstring"""






						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 					_lowerCamelCase (		self     :						Union[str, Any]				,	A     :						torch.Tensor)     ->					torch.Tensor:



						"""simple docstring"""






						_UpperCAmelCase	 =     self.conv(A)
						_UpperCAmelCase	 =     self.batch_norm(A)
						_UpperCAmelCase	 =     self.activation(A)

						return output







class     __lowerCAmelCase					(    nn.Module		):



			def __init__(		self     :						str				,	A     :						int				,	A     :						int				,	A     :						int)     ->					None:



						"""simple docstring"""






						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 					_lowerCamelCase (		self     :						Any				,	A     :						torch.Tensor)     ->					torch.Tensor:



						"""simple docstring"""






						_UpperCAmelCase	 =     input
						for layer in self.layers:
									_UpperCAmelCase	 =     layer(A)
						return hidden_state







class     __lowerCAmelCase					(    nn.Module		):



			def __init__(		self     :						Dict				,	A     :						Tuple[int, ...]				,	A     :						int				,	A     :						int				,	A     :						bool)     ->					None:



						"""simple docstring"""






						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 					_lowerCamelCase (		self     :						str				,	A     :						torch.Tensor)     ->					List[torch.Tensor]:



						"""simple docstring"""






						_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     __lowerCAmelCase					(    nn.Module		):



			def __init__(		self     :						Tuple				,	A     :						Tuple				,	A     :						List[str])     ->					Dict:



						"""simple docstring"""






						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 					_lowerCamelCase (		self     :						Tuple)     ->					Optional[int]:



						"""simple docstring"""






						self.apply(self._init_weights)



			def 					_lowerCamelCase (		self     :						Optional[Any]				,	A     :						Dict)     ->					Any:



						"""simple docstring"""






						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 					_lowerCamelCase (		self     :						Tuple				,	A     :						str)     ->					List[str]:



						"""simple docstring"""






						_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 					_lowerCamelCase (		self     :						List[str]				,	A     :						torch.Tensor)     ->					torch.Tensor:



						"""simple docstring"""






						_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     __lowerCAmelCase					(    nn.Module		):



			def __init__(		self     :						Any				,	A     :						List[str]				,	A     :						int = 2				,	A     :						int = 3				,	A     :						Union[int, Tuple[int, int]] = 1)     ->					None:



						"""simple docstring"""






						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 					_lowerCamelCase (		self     :						Any)     ->					Union[str, Any]:



						"""simple docstring"""






						self.apply(self._init_weights)



			def 					_lowerCamelCase (		self     :						Union[str, Any]				,	A     :						Optional[Any])     ->					Any:



						"""simple docstring"""






						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 					_lowerCamelCase (		self     :						Tuple				,	A     :						torch.Tensor)     ->					torch.Tensor:



						"""simple docstring"""






						_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     __lowerCAmelCase					(    A		):
			UpperCamelCase           =  UperNetConfig
			UpperCamelCase           =  '''pixel_values'''
			UpperCamelCase           =  True



			def 					_lowerCamelCase (		self     :						Any				,	A     :						str)     ->					Dict:



						"""simple docstring"""






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



			def 					_lowerCamelCase (		self     :						Tuple)     ->					str:



						"""simple docstring"""






						self.backbone.init_weights()
						self.decode_head.init_weights()
						self.auxiliary_head.init_weights()



			def 					_lowerCamelCase (		self     :						str				,	A     :						str				,	A     :						int=False)     ->					Dict:



						"""simple docstring"""






						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     __lowerCAmelCase					(    A		):



			def __init__(		self     :						Dict				,	A     :						Optional[int])     ->					int:



						"""simple docstring"""






						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 					_lowerCamelCase (		self     :						List[Any]				,	A     :						Optional[torch.Tensor] = None				,	A     :						Optional[bool] = None				,	A     :						Optional[bool] = None				,	A     :						Optional[torch.Tensor] = None				,	A     :						Optional[bool] = None				,	)     ->					Union[tuple, SemanticSegmenterOutput]:



						"""simple docstring"""






						_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 sympy import diff, lambdify, symbols
from sympy.functions import *  # noqa: F403





def 							A			(  _UpperCAmelCase       :     str							,     _UpperCAmelCase       :     complex							,     _UpperCAmelCase       :     str = "x"							,     _UpperCAmelCase       :     float = 10**-10							,     _UpperCAmelCase       :     int = 1							,     )       ->				complex:







			'''simple docstring'''
			_UpperCAmelCase	 =     symbols(_UpperCAmelCase					)
			_UpperCAmelCase	 =     lambdify(_UpperCAmelCase							,     _UpperCAmelCase					)
			_UpperCAmelCase	 =     lambdify(_UpperCAmelCase							,     diff(_UpperCAmelCase							,     _UpperCAmelCase					)					)

			_UpperCAmelCase	 =     starting_point

			while True:
						if diff_function(_UpperCAmelCase					) != 0:
									_UpperCAmelCase	 =     prev_guess - multiplicity * func(_UpperCAmelCase					) / diff_function(
									    _UpperCAmelCase					)
						else:
									raise ZeroDivisionError('Could not find root'					) from None

						# Precision is checked by comparing the difference of consecutive guesses
						if abs(next_guess - prev_guess					) < precision:
									return next_guess

						_UpperCAmelCase	 =     next_guess


# Let's Execute
if __name__ == "__main__":
							# Find root of trigonometric function
							# Find value of pi
							print(f"""The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}""")

							# Find root of polynomial
							# Find fourth Root of 5
							print(f"""The root of x**4 - 5 = 0 is {newton_raphson("x**4 -5", 0.4 +5J)}""")

							# Find value of e
							print(
							    "The root of log(y) - 1 = 0 is ",
							    f"""{newton_raphson("log(y) - 1", 2, variable="y")}""",
							)

							# Exponential Roots
							print(
							    "The root of exp(x) - 1 = 0 is",
							    f"""{newton_raphson("exp(x) - 1", 10, precision=0.005)}""",
							)

							# Find root of cos(x)
							print(f"""The root of cos(x) = 0 is {newton_raphson("cos(x)", 0)}""")
