

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

# General docstring
lowerCAmelCase							:  List[str]            =						"""UperNetConfig"""



class   __lowercase    (			nn.Module     ):




			"""simple docstring"""







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




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple       ,						lowerCAmelCase__  :					torch.Tensor):
									SCREAMING_SNAKE_CASE_:			Tuple  		=	self.conv(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			int  		=	self.batch_norm(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	self.activation(lowerCAmelCase__)

									return output







class   __lowercase    (			nn.Module     ):




			"""simple docstring"""







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




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]       ,						lowerCAmelCase__  :					torch.Tensor):
									SCREAMING_SNAKE_CASE_:			Dict  		=	input
									for layer in self.layers:
															SCREAMING_SNAKE_CASE_:			Tuple  		=	layer(lowerCAmelCase__)
									return hidden_state







class   __lowercase    (			nn.Module     ):




			"""simple docstring"""







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




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







class   __lowercase    (			nn.Module     ):




			"""simple docstring"""







			def __init__(			self  :					str       ,						lowerCAmelCase__  :					int       ,						lowerCAmelCase__  :					Any):
									super().__init__()

									SCREAMING_SNAKE_CASE_:			Tuple  		=	config
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	config.pool_scales  # e.g. (1, 2, 3, 6)
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	in_channels
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	config.hidden_size
									SCREAMING_SNAKE_CASE_:			Dict  		=	False
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	nn.Convad(self.channels       ,						config.num_labels       ,						kernel_size=1)

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

									SCREAMING_SNAKE_CASE_:			List[Any]  		=	UperNetConvModule(
									    len(self.in_channels) * self.channels       ,						self.channels       ,						kernel_size=3       ,						padding=1       ,						)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									self.apply(self._init_weights)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple       ,						lowerCAmelCase__  :					Dict):
									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 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[int]       ,						lowerCAmelCase__  :					Optional[int]):
									SCREAMING_SNAKE_CASE_:			str  		=	inputs[-1]
									SCREAMING_SNAKE_CASE_:			List[str]  		=	[x]
									psp_outs.extend(self.psp_modules(lowerCAmelCase__))
									SCREAMING_SNAKE_CASE_:			Tuple  		=	torch.cat(lowerCAmelCase__       ,						dim=1)
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	self.bottleneck(lowerCAmelCase__)

									return output




			def 	_SCREAMING_SNAKE_CASE      (			self  :					str       ,						lowerCAmelCase__  :					torch.Tensor):
									# build laterals
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	[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
									SCREAMING_SNAKE_CASE_:			Tuple  		=	len(lowerCAmelCase__)
									for i in range(used_backbone_levels - 1       ,						0       ,						-1):
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	laterals[i - 1].shape[2:]
															SCREAMING_SNAKE_CASE_:			Any  		=	laterals[i - 1] + nn.functional.interpolate(
															    laterals[i]       ,						size=lowerCAmelCase__       ,						mode="bilinear"       ,						align_corners=self.align_corners)

									# build outputs
									SCREAMING_SNAKE_CASE_:			Any  		=	[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):
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	nn.functional.interpolate(
															    fpn_outs[i]       ,						size=fpn_outs[0].shape[2:]       ,						mode="bilinear"       ,						align_corners=self.align_corners)
									SCREAMING_SNAKE_CASE_:			Dict  		=	torch.cat(lowerCAmelCase__       ,						dim=1)
									SCREAMING_SNAKE_CASE_:			List[str]  		=	self.fpn_bottleneck(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			int  		=	self.classifier(lowerCAmelCase__)

									return output







class   __lowercase    (			nn.Module     ):




			"""simple docstring"""







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

									SCREAMING_SNAKE_CASE_:			Any  		=	config
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	config.auxiliary_in_channels
									SCREAMING_SNAKE_CASE_:			str  		=	config.auxiliary_channels
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	config.auxiliary_num_convs
									SCREAMING_SNAKE_CASE_:			str  		=	config.auxiliary_concat_input
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	in_index

									SCREAMING_SNAKE_CASE_:			List[str]  		=	(kernel_size // 2) * dilation
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	[]
									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:
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	nn.Identity()
									else:
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	nn.Sequential(*lowerCAmelCase__)
									if self.concat_input:
															SCREAMING_SNAKE_CASE_:			Any  		=	UperNetConvModule(
															    self.in_channels + self.channels       ,						self.channels       ,						kernel_size=lowerCAmelCase__       ,						padding=kernel_size // 2)

									SCREAMING_SNAKE_CASE_:			Dict  		=	nn.Convad(self.channels       ,						config.num_labels       ,						kernel_size=1)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									self.apply(self._init_weights)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]       ,						lowerCAmelCase__  :					List[Any]):
									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 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple       ,						lowerCAmelCase__  :					torch.Tensor):
									# just take the relevant feature maps
									SCREAMING_SNAKE_CASE_:			str  		=	encoder_hidden_states[self.in_index]
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	self.convs(lowerCAmelCase__)
									if self.concat_input:
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	self.conv_cat(torch.cat([hidden_states, output]       ,						dim=1))
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	self.classifier(lowerCAmelCase__)
									return output







class   __lowercase    (			__UpperCamelCase     ):




			"""simple docstring"""







			_UpperCAmelCase       :							int      							=					UperNetConfig
			_UpperCAmelCase       :							int      							=					'''pixel_values'''
			_UpperCAmelCase       :							Union[str, Any]      							=					True



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]       ,						lowerCAmelCase__  :					Union[str, Any]):
									if isinstance(lowerCAmelCase__       ,						lowerCAmelCase__):
															module.backbone.init_weights()
															module.decode_head.init_weights()
															module.auxiliary_head.init_weights()



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str):
									self.backbone.init_weights()
									self.decode_head.init_weights()
									self.auxiliary_head.init_weights()




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Any       ,						lowerCAmelCase__  :					Dict       ,						lowerCAmelCase__  :					Optional[int]=False):
									if isinstance(lowerCAmelCase__       ,						lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_:			Any  		=	value







lowerCAmelCase							:  List[Any]            =						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							:  Union[str, Any]            =						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.'''		,	__UpperCamelCase		,	)
class   __lowercase    (			__UpperCamelCase     ):




			"""simple docstring"""







			def __init__(			self  :					Optional[int]       ,						lowerCAmelCase__  :					Union[str, Any]):
									super().__init__(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoBackbone.from_config(config.backbone_config)

									# Semantic segmentation head(s)
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	UperNetHead(lowerCAmelCase__       ,						in_channels=self.backbone.channels)
									SCREAMING_SNAKE_CASE_:			int  		=	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 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]       ,						lowerCAmelCase__  :					Optional[torch.Tensor] = None       ,						lowerCAmelCase__  :					Optional[bool] = None       ,						lowerCAmelCase__  :					Optional[bool] = None       ,						lowerCAmelCase__  :					Optional[torch.Tensor] = None       ,						lowerCAmelCase__  :					Optional[bool] = None       ,						):
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	return_dict if return_dict is not None else self.config.use_return_dict
									SCREAMING_SNAKE_CASE_:			int  		=	(
									    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
									)
									SCREAMING_SNAKE_CASE_:			str  		=	output_attentions if output_attentions is not None else self.config.output_attentions

									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	self.backbone.forward_with_filtered_kwargs(
									    lowerCAmelCase__       ,						output_hidden_states=lowerCAmelCase__       ,						output_attentions=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			List[str]  		=	outputs.feature_maps

									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	self.decode_head(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	nn.functional.interpolate(lowerCAmelCase__       ,						size=pixel_values.shape[2:]       ,						mode="bilinear"       ,						align_corners=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			List[str]  		=	None
									if self.auxiliary_head is not None:
															SCREAMING_SNAKE_CASE_:			List[Any]  		=	self.auxiliary_head(lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	nn.functional.interpolate(
															    lowerCAmelCase__       ,						size=pixel_values.shape[2:]       ,						mode="bilinear"       ,						align_corners=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			List[str]  		=	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
																					SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	CrossEntropyLoss(ignore_index=self.config.loss_ignore_index)
																					SCREAMING_SNAKE_CASE_:			str  		=	loss_fct(lowerCAmelCase__       ,						lowerCAmelCase__)
																					SCREAMING_SNAKE_CASE_:			Tuple  		=	loss_fct(lowerCAmelCase__       ,						lowerCAmelCase__)
																					SCREAMING_SNAKE_CASE_:			Tuple  		=	main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

									if not return_dict:
															if output_hidden_states:
																					SCREAMING_SNAKE_CASE_:			List[str]  		=	(logits,) + outputs[1:]
															else:
																					SCREAMING_SNAKE_CASE_:			int  		=	(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       ,						)





import tempfile
import unittest

import numpy as np

import transformers
from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
						import jax
						import jax.numpy as jnp

						from transformers.modeling_flax_pytorch_utils import (
						    convert_pytorch_state_dict_to_flax,
						    load_flax_weights_in_pytorch_model,
						)
						from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel

if is_torch_available():
						import torch



class   __lowercase    :




			"""simple docstring"""







			def __init__(			self  :					str       ,						lowerCAmelCase__  :					Dict       ,						lowerCAmelCase__  :					Dict=14       ,						lowerCAmelCase__  :					Optional[Any]=7       ,						lowerCAmelCase__  :					Optional[int]=True       ,						lowerCAmelCase__  :					Optional[int]=True       ,						lowerCAmelCase__  :					Union[str, Any]=False       ,						lowerCAmelCase__  :					Tuple=True       ,						lowerCAmelCase__  :					Optional[int]=99       ,						lowerCAmelCase__  :					str=32       ,						lowerCAmelCase__  :					Any=4       ,						lowerCAmelCase__  :					Any=4       ,						lowerCAmelCase__  :					Any=4       ,						lowerCAmelCase__  :					Dict=37       ,						lowerCAmelCase__  :					Tuple="gelu"       ,						lowerCAmelCase__  :					str=0.1       ,						lowerCAmelCase__  :					Optional[Any]=0.1       ,						lowerCAmelCase__  :					Dict=512       ,						lowerCAmelCase__  :					Dict=0.02       ,						):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	parent
									SCREAMING_SNAKE_CASE_:			Any  		=	batch_size
									SCREAMING_SNAKE_CASE_:			str  		=	seq_length
									SCREAMING_SNAKE_CASE_:			Dict  		=	is_training
									SCREAMING_SNAKE_CASE_:			str  		=	use_input_mask
									SCREAMING_SNAKE_CASE_:			int  		=	use_token_type_ids
									SCREAMING_SNAKE_CASE_:			Tuple  		=	use_labels
									SCREAMING_SNAKE_CASE_:			int  		=	vocab_size
									SCREAMING_SNAKE_CASE_:			Tuple  		=	hidden_size
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	rotary_dim
									SCREAMING_SNAKE_CASE_:			Dict  		=	num_hidden_layers
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	num_attention_heads
									SCREAMING_SNAKE_CASE_:			Dict  		=	intermediate_size
									SCREAMING_SNAKE_CASE_:			List[str]  		=	hidden_act
									SCREAMING_SNAKE_CASE_:			List[str]  		=	hidden_dropout_prob
									SCREAMING_SNAKE_CASE_:			int  		=	attention_probs_dropout_prob
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	max_position_embeddings
									SCREAMING_SNAKE_CASE_:			int  		=	initializer_range
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	None
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	vocab_size - 1
									SCREAMING_SNAKE_CASE_:			Tuple  		=	vocab_size - 1
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	vocab_size - 1



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	ids_tensor([self.batch_size, self.seq_length]       ,						self.vocab_size)

									SCREAMING_SNAKE_CASE_:			Any  		=	None
									if self.use_input_mask:
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	random_attention_mask([self.batch_size, self.seq_length])

									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	GPTJConfig(
									    vocab_size=self.vocab_size       ,						n_embd=self.hidden_size       ,						n_layer=self.num_hidden_layers       ,						n_head=self.num_attention_heads       ,						n_positions=self.max_position_embeddings       ,						use_cache=lowerCAmelCase__       ,						bos_token_id=self.bos_token_id       ,						eos_token_id=self.eos_token_id       ,						pad_token_id=self.pad_token_id       ,						rotary_dim=self.rotary_dim       ,						)

									return (config, input_ids, input_mask)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	self.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Any  		=	config_and_inputs
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	{"input_ids": input_ids, "attention_mask": attention_mask}
									return config, inputs_dict



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Dict       ,						lowerCAmelCase__  :					Optional[Any]       ,						lowerCAmelCase__  :					Optional[Any]       ,						lowerCAmelCase__  :					Tuple       ,						lowerCAmelCase__  :					Optional[int]):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	20
									SCREAMING_SNAKE_CASE_:			Any  		=	model_class_name(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			str  		=	model.init_cache(input_ids.shape[0]       ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Any  		=	jnp.ones((input_ids.shape[0], max_decoder_length)       ,						dtype="i4")

									SCREAMING_SNAKE_CASE_:			List[str]  		=	jnp.broadcast_to(
									    jnp.arange(input_ids.shape[-1] - 1)[None, :]       ,						(input_ids.shape[0], input_ids.shape[-1] - 1))
									SCREAMING_SNAKE_CASE_:			int  		=	model(
									    input_ids[:, :-1]       ,						attention_mask=lowerCAmelCase__       ,						past_key_values=lowerCAmelCase__       ,						position_ids=lowerCAmelCase__       ,						)

									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]       ,						dtype="i4")
									SCREAMING_SNAKE_CASE_:			Dict  		=	model(
									    input_ids[:, -1:]       ,						attention_mask=lowerCAmelCase__       ,						past_key_values=outputs_cache.past_key_values       ,						position_ids=lowerCAmelCase__       ,						)

									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	model(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			List[Any]  		=	np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
									self.parent.assertTrue(diff < 1E-3       ,						msg=F"Max diff is {diff}")




			def 	_SCREAMING_SNAKE_CASE      (			self  :					str       ,						lowerCAmelCase__  :					Any       ,						lowerCAmelCase__  :					str       ,						lowerCAmelCase__  :					Dict       ,						lowerCAmelCase__  :					Tuple):
									SCREAMING_SNAKE_CASE_:			int  		=	20
									SCREAMING_SNAKE_CASE_:			Tuple  		=	model_class_name(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	jnp.concatenate(
									    [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]))]       ,						axis=-1       ,						)

									SCREAMING_SNAKE_CASE_:			List[str]  		=	model.init_cache(input_ids.shape[0]       ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	jnp.broadcast_to(
									    jnp.arange(input_ids.shape[-1] - 1)[None, :]       ,						(input_ids.shape[0], input_ids.shape[-1] - 1))

									SCREAMING_SNAKE_CASE_:			Any  		=	model(
									    input_ids[:, :-1]       ,						attention_mask=lowerCAmelCase__       ,						past_key_values=lowerCAmelCase__       ,						position_ids=lowerCAmelCase__       ,						)
									SCREAMING_SNAKE_CASE_:			int  		=	jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]       ,						dtype="i4")
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	model(
									    input_ids[:, -1:]       ,						past_key_values=outputs_cache.past_key_values       ,						attention_mask=lowerCAmelCase__       ,						position_ids=lowerCAmelCase__       ,						)

									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	model(lowerCAmelCase__       ,						attention_mask=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Dict  		=	np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
									self.parent.assertTrue(diff < 1E-3       ,						msg=F"Max diff is {diff}")







@require_flax
class   __lowercase    (			UpperCAmelCase_		,	UpperCAmelCase_		,	unittest.TestCase     ):




			"""simple docstring"""







			_UpperCAmelCase       :							Dict      							=					(FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else ()
			_UpperCAmelCase       :							Tuple      							=					(FlaxGPTJForCausalLM,) if is_flax_available() else ()



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									SCREAMING_SNAKE_CASE_:			Tuple  		=	FlaxGPTJModelTester(self)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[int]):
									for model_class_name in self.all_model_classes:
															SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			str  		=	self.model_tester.prepare_config_and_inputs()
															self.model_tester.check_use_cache_forward(lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Any):
									for model_class_name in self.all_model_classes:
															SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Any  		=	self.model_tester.prepare_config_and_inputs()
															self.model_tester.check_use_cache_forward_with_attn_mask(
															    lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__)



			@tooslow
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Any):
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	GPTaTokenizer.from_pretrained("gpt2"       ,						pad_token="<|endoftext|>"       ,						padding_side="left")
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	tokenizer(["Hello this is a long string", "Hey"]       ,						return_tensors="np"       ,						padding=lowerCAmelCase__       ,						truncation=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Tuple  		=	FlaxGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B")
									SCREAMING_SNAKE_CASE_:			int  		=	False
									SCREAMING_SNAKE_CASE_:			str  		=	model.config.eos_token_id

									SCREAMING_SNAKE_CASE_:			int  		=	jax.jit(model.generate)

									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	jit_generate(
									    inputs["input_ids"]       ,						attention_mask=inputs["attention_mask"]       ,						pad_token_id=tokenizer.pad_token_id).sequences

									SCREAMING_SNAKE_CASE_:			int  		=	tokenizer.batch_decode(lowerCAmelCase__       ,						skip_special_tokens=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			List[str]  		=	[
									    "Hello this is a long string of text.\n\nI'm trying to get the text of the",
									    "Hey, I'm a little late to the party. I'm going to",
									]

									self.assertListEqual(lowerCAmelCase__       ,						lowerCAmelCase__)



			@is_pt_flax_cross_test
			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															with self.subTest(model_class.__name__):
																					# prepare inputs
																					SCREAMING_SNAKE_CASE_:			Tuple  		=	self._prepare_for_class(lowerCAmelCase__       ,						lowerCAmelCase__)
																					SCREAMING_SNAKE_CASE_:			List[Any]  		=	{k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()}

																					# load corresponding PyTorch class
																					SCREAMING_SNAKE_CASE_:			Tuple  		=	model_class.__name__[4:]  # Skip the "Flax" at the beginning
																					SCREAMING_SNAKE_CASE_:			int  		=	getattr(lowerCAmelCase__       ,						lowerCAmelCase__)

																					SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	pt_inputs["input_ids"].shape
																					SCREAMING_SNAKE_CASE_:			List[Any]  		=	np.random.randint(0       ,						seq_length - 1       ,						size=(batch_size,))
																					for batch_idx, start_index in enumerate(lowerCAmelCase__):
																											SCREAMING_SNAKE_CASE_:			Dict  		=	0
																											SCREAMING_SNAKE_CASE_:			str  		=	1
																											SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	0
																											SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	1
																					SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	pt_model_class(lowerCAmelCase__).eval()
																					SCREAMING_SNAKE_CASE_:			Tuple  		=	model_class(lowerCAmelCase__       ,						dtype=jnp.floataa)

																					SCREAMING_SNAKE_CASE_:			Optional[int]  		=	convert_pytorch_state_dict_to_flax(pt_model.state_dict()       ,						lowerCAmelCase__)
																					SCREAMING_SNAKE_CASE_:			List[str]  		=	fx_state

																					with torch.no_grad():
																											SCREAMING_SNAKE_CASE_:			Optional[int]  		=	pt_model(**lowerCAmelCase__).to_tuple()

																					SCREAMING_SNAKE_CASE_:			List[str]  		=	fx_model(**lowerCAmelCase__).to_tuple()
																					self.assertEqual(len(lowerCAmelCase__)       ,						len(lowerCAmelCase__)       ,						"Output lengths differ between Flax and PyTorch")
																					for fx_output, pt_output in zip(lowerCAmelCase__       ,						lowerCAmelCase__):
																											self.assert_almost_equals(fx_output[:, -1]       ,						pt_output[:, -1].numpy()       ,						4E-2)

																					with tempfile.TemporaryDirectory() as tmpdirname:
																											pt_model.save_pretrained(lowerCAmelCase__)
																											SCREAMING_SNAKE_CASE_:			int  		=	model_class.from_pretrained(lowerCAmelCase__       ,						from_pt=lowerCAmelCase__)

																					SCREAMING_SNAKE_CASE_:			List[str]  		=	fx_model_loaded(**lowerCAmelCase__).to_tuple()
																					self.assertEqual(
																					    len(lowerCAmelCase__)       ,						len(lowerCAmelCase__)       ,						"Output lengths differ between Flax and PyTorch")
																					for fx_output_loaded, pt_output in zip(lowerCAmelCase__       ,						lowerCAmelCase__):
																											self.assert_almost_equals(fx_output_loaded[:, -1]       ,						pt_output[:, -1].numpy()       ,						4E-2)



			@is_pt_flax_cross_test
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	self.model_tester.prepare_config_and_inputs_for_common()
									for model_class in self.all_model_classes:
															with self.subTest(model_class.__name__):
																					# prepare inputs
																					SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	self._prepare_for_class(lowerCAmelCase__       ,						lowerCAmelCase__)
																					SCREAMING_SNAKE_CASE_:			Optional[int]  		=	{k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()}

																					# load corresponding PyTorch class
																					SCREAMING_SNAKE_CASE_:			Optional[int]  		=	model_class.__name__[4:]  # Skip the "Flax" at the beginning
																					SCREAMING_SNAKE_CASE_:			Any  		=	getattr(lowerCAmelCase__       ,						lowerCAmelCase__)

																					SCREAMING_SNAKE_CASE_:			Optional[int]  		=	pt_model_class(lowerCAmelCase__).eval()
																					SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	model_class(lowerCAmelCase__       ,						dtype=jnp.floataa)

																					SCREAMING_SNAKE_CASE_:			int  		=	load_flax_weights_in_pytorch_model(lowerCAmelCase__       ,						fx_model.params)
																					SCREAMING_SNAKE_CASE_		,   SCREAMING_SNAKE_CASE_:			int  		=	pt_inputs["input_ids"].shape
																					SCREAMING_SNAKE_CASE_:			Any  		=	np.random.randint(0       ,						seq_length - 1       ,						size=(batch_size,))
																					for batch_idx, start_index in enumerate(lowerCAmelCase__):
																											SCREAMING_SNAKE_CASE_:			str  		=	0
																											SCREAMING_SNAKE_CASE_:			Tuple  		=	1
																											SCREAMING_SNAKE_CASE_:			Dict  		=	0
																											SCREAMING_SNAKE_CASE_:			str  		=	1

																					# make sure weights are tied in PyTorch
																					pt_model.tie_weights()

																					with torch.no_grad():
																											SCREAMING_SNAKE_CASE_:			Optional[int]  		=	pt_model(**lowerCAmelCase__).to_tuple()

																					SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	fx_model(**lowerCAmelCase__).to_tuple()
																					self.assertEqual(len(lowerCAmelCase__)       ,						len(lowerCAmelCase__)       ,						"Output lengths differ between Flax and PyTorch")
																					for fx_output, pt_output in zip(lowerCAmelCase__       ,						lowerCAmelCase__):
																											self.assert_almost_equals(fx_output[:, -1]       ,						pt_output[:, -1].numpy()       ,						4E-2)

																					with tempfile.TemporaryDirectory() as tmpdirname:
																											fx_model.save_pretrained(lowerCAmelCase__)
																											SCREAMING_SNAKE_CASE_:			Any  		=	pt_model_class.from_pretrained(lowerCAmelCase__       ,						from_flax=lowerCAmelCase__)

																					with torch.no_grad():
																											SCREAMING_SNAKE_CASE_:			Any  		=	pt_model_loaded(**lowerCAmelCase__).to_tuple()

																					self.assertEqual(
																					    len(lowerCAmelCase__)       ,						len(lowerCAmelCase__)       ,						"Output lengths differ between Flax and PyTorch")
																					for fx_output, pt_output in zip(lowerCAmelCase__       ,						lowerCAmelCase__):
																											self.assert_almost_equals(fx_output[:, -1]       ,						pt_output[:, -1].numpy()       ,						4E-2)




			@tooslow
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									for model_class_name in self.all_model_classes:
															SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	model_class_name.from_pretrained("EleutherAI/gpt-j-6B")
															SCREAMING_SNAKE_CASE_:			str  		=	model(np.ones((1, 1)))
															self.assertIsNotNone(lowerCAmelCase__)






