


'''simple docstring'''

import tempfile
import unittest

import numpy as np

import transformers
from transformers import GPTaConfig, GPTaTokenizer, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, 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.gpta.modeling_flax_gpta import FlaxGPTaLMHeadModel, FlaxGPTaModel

if is_torch_available():
	import torch


class    a__					:







				"""simple docstring"""



				def __init__(self							,      __lowercase							,      __lowercase=14							,      __lowercase=7							,      __lowercase=True							,      __lowercase=True							,      __lowercase=False							,      __lowercase=True							,      __lowercase=99							,      __lowercase=32							,      __lowercase=5							,      __lowercase=4							,      __lowercase=37							,      __lowercase="gelu"							,      __lowercase=0.1							,      __lowercase=0.1							,      __lowercase=5_12							,      __lowercase=0.0_2							,      ):
										__lowerCAmelCase											=					parent
										__lowerCAmelCase											=					batch_size
										__lowerCAmelCase											=					seq_length
										__lowerCAmelCase											=					is_training
										__lowerCAmelCase											=					use_input_mask
										__lowerCAmelCase											=					use_token_type_ids
										__lowerCAmelCase											=					use_labels
										__lowerCAmelCase											=					vocab_size
										__lowerCAmelCase											=					hidden_size
										__lowerCAmelCase											=					num_hidden_layers
										__lowerCAmelCase											=					num_attention_heads
										__lowerCAmelCase											=					intermediate_size
										__lowerCAmelCase											=					hidden_act
										__lowerCAmelCase											=					hidden_dropout_prob
										__lowerCAmelCase											=					attention_probs_dropout_prob
										__lowerCAmelCase											=					max_position_embeddings
										__lowerCAmelCase											=					initializer_range
										__lowerCAmelCase											=					None
										__lowerCAmelCase											=					vocab_size - 1
										__lowerCAmelCase											=					vocab_size - 1
										__lowerCAmelCase											=					vocab_size - 1




				def        _snake_case	(self		):
										__lowerCAmelCase											=					ids_tensor([self.batch_size, self.seq_length]							,      self.vocab_size		)

										__lowerCAmelCase											=					None
										if self.use_input_mask:
																__lowerCAmelCase											=					random_attention_mask([self.batch_size, self.seq_length]		)

										__lowerCAmelCase											=					GPTaConfig(
										    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=__lowercase							,      bos_token_id=self.bos_token_id							,      eos_token_id=self.eos_token_id							,      pad_token_id=self.pad_token_id							,      )

										return (config, input_ids, input_mask)




				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.prepare_config_and_inputs()
										__lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase											=					config_and_inputs
										__lowerCAmelCase											=					{'''input_ids''': input_ids, '''attention_mask''': attention_mask}
										return config, inputs_dict




				def        _snake_case	(self		):
										__lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase											=					self.prepare_config_and_inputs()

										__lowerCAmelCase											=					floats_tensor([self.batch_size, self.seq_length, self.hidden_size]		)
										__lowerCAmelCase											=					ids_tensor([self.batch_size, self.seq_length]							,      vocab_size=2		)

										return (
										    config,
										    input_ids,
										    attention_mask,
										    encoder_hidden_states,
										    encoder_attention_mask,
										)




				def        _snake_case	(self							,      __lowercase							,      __lowercase							,      __lowercase							,      __lowercase		):
										__lowerCAmelCase											=					20
										__lowerCAmelCase											=					model_class_name(__lowercase		)

										__lowerCAmelCase											=					model.init_cache(input_ids.shape[0]							,      __lowercase		)
										__lowerCAmelCase											=					jnp.ones((input_ids.shape[0], max_decoder_length)							,      dtype='''i4'''		)

										__lowerCAmelCase											=					jnp.broadcast_to(
										    jnp.arange(input_ids.shape[-1] - 1		)[None, :]							,      (input_ids.shape[0], input_ids.shape[-1] - 1)		)
										__lowerCAmelCase											=					model(
										    input_ids[:, :-1]							,      attention_mask=__lowercase							,      past_key_values=__lowercase							,      position_ids=__lowercase							,      )

										__lowerCAmelCase											=					jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]							,      dtype='''i4'''		)
										__lowerCAmelCase											=					model(
										    input_ids[:, -1:]							,      attention_mask=__lowercase							,      past_key_values=outputs_cache.past_key_values							,      position_ids=__lowercase							,      )

										__lowerCAmelCase											=					model(__lowercase		)

										__lowerCAmelCase											=					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        _snake_case	(self							,      __lowercase							,      __lowercase							,      __lowercase							,      __lowercase		):
										__lowerCAmelCase											=					20
										__lowerCAmelCase											=					model_class_name(__lowercase		)

										__lowerCAmelCase											=					jnp.concatenate(
										    [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])		)]							,      axis=-1							,      )

										__lowerCAmelCase											=					model.init_cache(input_ids.shape[0]							,      __lowercase		)
										__lowerCAmelCase											=					jnp.broadcast_to(
										    jnp.arange(input_ids.shape[-1] - 1		)[None, :]							,      (input_ids.shape[0], input_ids.shape[-1] - 1)		)

										__lowerCAmelCase											=					model(
										    input_ids[:, :-1]							,      attention_mask=__lowercase							,      past_key_values=__lowercase							,      position_ids=__lowercase							,      )
										__lowerCAmelCase											=					jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]							,      dtype='''i4'''		)
										__lowerCAmelCase											=					model(
										    input_ids[:, -1:]							,      past_key_values=outputs_cache.past_key_values							,      attention_mask=__lowercase							,      position_ids=__lowercase							,      )

										__lowerCAmelCase											=					model(__lowercase							,      attention_mask=__lowercase		)

										__lowerCAmelCase											=					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    a__					(			__A				,    __A				,    unittest.TestCase   ):







				"""simple docstring"""



				__UpperCamelCase     :		Dict						=						(FlaxGPTaModel, FlaxGPTaLMHeadModel) if is_flax_available() else ()
				__UpperCamelCase     :		Dict						=						(FlaxGPTaLMHeadModel,) if is_flax_available() else ()




				def        _snake_case	(self		):
										__lowerCAmelCase											=					FlaxGPTaModelTester(self		)




				def        _snake_case	(self		):
										for model_class_name in self.all_model_classes:
																__lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase											=					self.model_tester.prepare_config_and_inputs()
																self.model_tester.check_use_cache_forward(__lowercase							,      __lowercase							,      __lowercase							,      __lowercase		)




				def        _snake_case	(self		):
										for model_class_name in self.all_model_classes:
																__lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase											=					self.model_tester.prepare_config_and_inputs()
																self.model_tester.check_use_cache_forward_with_attn_mask(
																    __lowercase							,      __lowercase							,      __lowercase							,      __lowercase		)




				@slow
				def        _snake_case	(self		):
										__lowerCAmelCase											=					GPTaTokenizer.from_pretrained('''gpt2'''							,      pad_token='''</s>'''							,      padding_side='''left'''		)
										__lowerCAmelCase											=					tokenizer(['''Hello this is a long string''', '''Hey''']							,      return_tensors='''np'''							,      padding=__lowercase							,      truncation=__lowercase		)

										__lowerCAmelCase											=					FlaxGPTaLMHeadModel.from_pretrained('''gpt2'''		)
										__lowerCAmelCase											=					False
										__lowerCAmelCase											=					model.config.eos_token_id

										__lowerCAmelCase											=					jax.jit(model.generate		)

										__lowerCAmelCase											=					jit_generate(inputs['''input_ids''']							,      attention_mask=inputs['''attention_mask''']		).sequences

										__lowerCAmelCase											=					tokenizer.batch_decode(__lowercase							,      skip_special_tokens=__lowercase		)

										__lowerCAmelCase											=					[
										    '''Hello this is a long string of words. I\'m going to start with the first one.\n''',
										    '''Hey, I\'m not sure if I\'m going to be able to do''',
										]

										self.assertListEqual(__lowercase							,      __lowercase		)




				@is_pt_flax_cross_test
				def        _snake_case	(self		):
										__lowerCAmelCase							,       __lowerCAmelCase											=					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
																						__lowerCAmelCase											=					self._prepare_for_class(__lowercase							,      __lowercase		)
																						__lowerCAmelCase											=					{k: torch.tensor(v.tolist()		) for k, v in prepared_inputs_dict.items()}

																						# load corresponding PyTorch class
																						__lowerCAmelCase											=					model_class.__name__[4:]  # Skip the "Flax" at the beginning
																						__lowerCAmelCase											=					getattr(__lowercase							,      __lowercase		)

																						__lowerCAmelCase							,       __lowerCAmelCase											=					pt_inputs['''input_ids'''].shape
																						__lowerCAmelCase											=					np.random.randint(0							,      seq_length - 1							,      size=(batch_size,)		)
																						for batch_idx, start_index in enumerate(__lowercase		):
																												__lowerCAmelCase											=					0
																												__lowerCAmelCase											=					1
																												__lowerCAmelCase											=					0
																												__lowerCAmelCase											=					1
																						__lowerCAmelCase											=					pt_model_class(__lowercase		).eval()
																						__lowerCAmelCase											=					model_class(__lowercase							,      dtype=jnp.floataa		)

																						__lowerCAmelCase											=					convert_pytorch_state_dict_to_flax(pt_model.state_dict()							,      __lowercase		)
																						__lowerCAmelCase											=					fx_state

																						with torch.no_grad():
																												__lowerCAmelCase											=					pt_model(**__lowercase		).to_tuple()

																						__lowerCAmelCase											=					fx_model(**__lowercase		).to_tuple()
																						self.assertEqual(len(__lowercase		)							,      len(__lowercase		)							,      '''Output lengths differ between Flax and PyTorch'''		)
																						for fx_output, pt_output in zip(__lowercase							,      __lowercase		):
																												self.assert_almost_equals(fx_output[:, -1]							,      pt_output[:, -1].numpy()							,      4e-2		)

																						with tempfile.TemporaryDirectory() as tmpdirname:
																												pt_model.save_pretrained(__lowercase		)
																												__lowerCAmelCase											=					model_class.from_pretrained(__lowercase							,      from_pt=__lowercase		)

																						__lowerCAmelCase											=					fx_model_loaded(**__lowercase		).to_tuple()
																						self.assertEqual(
																						    len(__lowercase		)							,      len(__lowercase		)							,      '''Output lengths differ between Flax and PyTorch'''		)
																						for fx_output_loaded, pt_output in zip(__lowercase							,      __lowercase		):
																												self.assert_almost_equals(fx_output_loaded[:, -1]							,      pt_output[:, -1].numpy()							,      4e-2		)




				@is_pt_flax_cross_test
				def        _snake_case	(self		):
										__lowerCAmelCase							,       __lowerCAmelCase											=					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
																						__lowerCAmelCase											=					self._prepare_for_class(__lowercase							,      __lowercase		)
																						__lowerCAmelCase											=					{k: torch.tensor(v.tolist()		) for k, v in prepared_inputs_dict.items()}

																						# load corresponding PyTorch class
																						__lowerCAmelCase											=					model_class.__name__[4:]  # Skip the "Flax" at the beginning
																						__lowerCAmelCase											=					getattr(__lowercase							,      __lowercase		)

																						__lowerCAmelCase											=					pt_model_class(__lowercase		).eval()
																						__lowerCAmelCase											=					model_class(__lowercase							,      dtype=jnp.floataa		)

																						__lowerCAmelCase											=					load_flax_weights_in_pytorch_model(__lowercase							,      fx_model.params		)
																						__lowerCAmelCase							,       __lowerCAmelCase											=					pt_inputs['''input_ids'''].shape
																						__lowerCAmelCase											=					np.random.randint(0							,      seq_length - 1							,      size=(batch_size,)		)
																						for batch_idx, start_index in enumerate(__lowercase		):
																												__lowerCAmelCase											=					0
																												__lowerCAmelCase											=					1
																												__lowerCAmelCase											=					0
																												__lowerCAmelCase											=					1

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

																						with torch.no_grad():
																												__lowerCAmelCase											=					pt_model(**__lowercase		).to_tuple()

																						__lowerCAmelCase											=					fx_model(**__lowercase		).to_tuple()
																						self.assertEqual(len(__lowercase		)							,      len(__lowercase		)							,      '''Output lengths differ between Flax and PyTorch'''		)
																						for fx_output, pt_output in zip(__lowercase							,      __lowercase		):
																												self.assert_almost_equals(fx_output[:, -1]							,      pt_output[:, -1].numpy()							,      4e-2		)

																						with tempfile.TemporaryDirectory() as tmpdirname:
																												fx_model.save_pretrained(__lowercase		)
																												__lowerCAmelCase											=					pt_model_class.from_pretrained(__lowercase							,      from_flax=__lowercase		)

																						with torch.no_grad():
																												__lowerCAmelCase											=					pt_model_loaded(**__lowercase		).to_tuple()

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




				@slow
				def        _snake_case	(self		):
										for model_class_name in self.all_model_classes:
																__lowerCAmelCase											=					model_class_name.from_pretrained('''gpt2'''							,      from_pt=__lowercase		)
																__lowerCAmelCase											=					model(np.ones((1, 1)		)		)
																self.assertIsNotNone(__lowercase		)





'''simple docstring'''

import inspect
from typing import Callable, List, Optional, Set, Tuple, Union

import torch
from packaging import version
from safetensors.torch import storage_ptr, storage_size
from torch import nn

from .utils import logging


_UpperCAmelCase					:			Optional[Any]				     =					[nn.LayerNorm]

_UpperCAmelCase					:			Dict				     =					logging.get_logger(__name__)

_UpperCAmelCase					:			Tuple				     =					version.parse(version.parse(torch.__version__).base_version)

_UpperCAmelCase					:			Optional[int]				     =					parsed_torch_version_base >= version.parse("""2.0""")
_UpperCAmelCase					:			Optional[int]				     =					parsed_torch_version_base >= version.parse("""1.12""")
_UpperCAmelCase					:			List[str]				     =					parsed_torch_version_base >= version.parse("""1.11""")
_UpperCAmelCase					:			Optional[int]				     =					parsed_torch_version_base < version.parse("""1.11""")

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase,					lowerCamelCase,					self):
						from torch import _softmax_backward_data

						if is_torch_less_than_1_11:
												return _softmax_backward_data(lowerCamelCase,					lowerCamelCase,					parent.dim,					self)
						else:
												return _softmax_backward_data(lowerCamelCase,					lowerCamelCase,					parent.dim,					self.dtype)

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase = 0):
						__lowerCAmelCase											=					index.to(layer.weight.device)
						__lowerCAmelCase											=					layer.weight.index_select(lowerCamelCase,					lowerCamelCase).clone().detach()
						if layer.bias is not None:
												if dim == 1:
																		__lowerCAmelCase											=					layer.bias.clone().detach()
												else:
																		__lowerCAmelCase											=					layer.bias[index].clone().detach()
						__lowerCAmelCase											=					list(layer.weight.size())
						__lowerCAmelCase											=					len(lowerCamelCase)
						__lowerCAmelCase											=					nn.Linear(new_size[1],					new_size[0],					bias=layer.bias is not None).to(layer.weight.device)
						__lowerCAmelCase											=					False
						new_layer.weight.copy_(W.contiguous())
						__lowerCAmelCase											=					True
						if layer.bias is not None:
												__lowerCAmelCase											=					False
												new_layer.bias.copy_(b.contiguous())
												__lowerCAmelCase											=					True
						return new_layer


class    a__					(			nn.Module   ):







				"""simple docstring"""



				def __init__(self							,      __lowercase							,      __lowercase		):
										super().__init__()
										__lowerCAmelCase											=					nf
										__lowerCAmelCase											=					nn.Parameter(torch.empty(__lowercase							,      __lowercase		)		)
										__lowerCAmelCase											=					nn.Parameter(torch.zeros(__lowercase		)		)
										nn.init.normal_(self.weight							,      std=0.0_2		)




				def        _snake_case	(self							,      __lowercase		):
										__lowerCAmelCase											=					x.size()[:-1] + (self.nf,)
										__lowerCAmelCase											=					torch.addmm(self.bias							,      x.view(-1							,      x.size(-1		)		)							,      self.weight		)
										__lowerCAmelCase											=					x.view(__lowercase		)
										return x

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase = 1):
						__lowerCAmelCase											=					index.to(layer.weight.device)
						__lowerCAmelCase											=					layer.weight.index_select(lowerCamelCase,					lowerCamelCase).clone().detach()
						if dim == 0:
												__lowerCAmelCase											=					layer.bias.clone().detach()
						else:
												__lowerCAmelCase											=					layer.bias[index].clone().detach()
						__lowerCAmelCase											=					list(layer.weight.size())
						__lowerCAmelCase											=					len(lowerCamelCase)
						__lowerCAmelCase											=					ConvaD(new_size[1],					new_size[0]).to(layer.weight.device)
						__lowerCAmelCase											=					False
						new_layer.weight.copy_(W.contiguous())
						__lowerCAmelCase											=					True
						__lowerCAmelCase											=					False
						new_layer.bias.copy_(b.contiguous())
						__lowerCAmelCase											=					True
						return new_layer

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase = None):
						if isinstance(lowerCamelCase,					nn.Linear):
												return prune_linear_layer(lowerCamelCase,					lowerCamelCase,					dim=0 if dim is None else dim)
						elif isinstance(lowerCamelCase,					lowerCamelCase):
												return prune_convad_layer(lowerCamelCase,					lowerCamelCase,					dim=1 if dim is None else dim)
						else:
												raise ValueError(F"""Can't prune layer of class {layer.__class__}""")

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase,					*lowerCamelCase):
						assert len(lowerCamelCase) > 0, F"""{input_tensors} has to be a tuple/list of tensors"""

						# inspect.signature exist since python 3.5 and is a python method -> no problem with backward compatibility
						__lowerCAmelCase											=					len(inspect.signature(lowerCamelCase).parameters)
						if num_args_in_forward_chunk_fn != len(lowerCamelCase):
												raise ValueError(
												    F"""forward_chunk_fn expects {num_args_in_forward_chunk_fn} arguments, but only {len(lowerCamelCase)} input """
												    '''tensors are given''')

						if chunk_size > 0:
												__lowerCAmelCase											=					input_tensors[0].shape[chunk_dim]
												for input_tensor in input_tensors:
																		if input_tensor.shape[chunk_dim] != tensor_shape:
																								raise ValueError(
																								    F"""All input tenors have to be of the same shape: {tensor_shape}, """
																								    F"""found shape {input_tensor.shape[chunk_dim]}""")

												if input_tensors[0].shape[chunk_dim] % chunk_size != 0:
																		raise ValueError(
																		    F"""The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk """
																		    F"""size {chunk_size}""")

												__lowerCAmelCase											=					input_tensors[0].shape[chunk_dim] // chunk_size

												# chunk input tensor into tuples
												__lowerCAmelCase											=					tuple(input_tensor.chunk(lowerCamelCase,					dim=lowerCamelCase) for input_tensor in input_tensors)
												# apply forward fn to every tuple
												__lowerCAmelCase											=					tuple(forward_fn(*lowerCamelCase) for input_tensors_chunk in zip(*lowerCamelCase))
												# concatenate output at same dimension
												return torch.cat(lowerCamelCase,					dim=lowerCamelCase)

						return forward_fn(*lowerCamelCase)

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase,					lowerCamelCase):
						__lowerCAmelCase											=					torch.ones(lowerCamelCase,					lowerCamelCase)
						__lowerCAmelCase											=					set(lowerCamelCase) - already_pruned_heads  # Convert to set and remove already pruned heads
						for head in heads:
												# Compute how many pruned heads are before the head and move the index accordingly
												__lowerCAmelCase											=					head - sum(1 if h < head else 0 for h in already_pruned_heads)
												__lowerCAmelCase											=					0
						__lowerCAmelCase											=					mask.view(-1).contiguous().eq(1)
						__lowerCAmelCase											=					torch.arange(len(lowerCamelCase))[mask].long()
						return heads, index

def 				__magic_name__(    *lowerCamelCase,					lowerCamelCase = None):
						return torch.meshgrid(*lowerCamelCase,					indexing=lowerCamelCase)




def 				__magic_name__(    lowerCamelCase):
						return tensor.device, storage_ptr(lowerCamelCase), storage_size(lowerCamelCase)

