





'''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  lowerCamelCase__				:


	"""simple docstring"""





	def __init__(					self   ,     UpperCAmelCase__   ,     UpperCAmelCase__=1_4   ,     UpperCAmelCase__=7   ,     UpperCAmelCase__=True   ,     UpperCAmelCase__=True   ,     UpperCAmelCase__=False   ,     UpperCAmelCase__=True   ,     UpperCAmelCase__=9_9   ,     UpperCAmelCase__=3_2   ,     UpperCAmelCase__=5   ,     UpperCAmelCase__=4   ,     UpperCAmelCase__=3_7   ,     UpperCAmelCase__="gelu"   ,     UpperCAmelCase__=0.1   ,     UpperCAmelCase__=0.1   ,     UpperCAmelCase__=5_1_2   ,     UpperCAmelCase__=0.0_2   ,     )       ->				str:
					_A :				List[str]				=  parent
					_A :				Optional[int]				=  batch_size
					_A :				Union[str, Any]				=  seq_length
					_A :				Optional[int]				=  is_training
					_A :				int				=  use_input_mask
					_A :				Optional[Any]				=  use_token_type_ids
					_A :				Tuple				=  use_labels
					_A :				str				=  vocab_size
					_A :				int				=  hidden_size
					_A :				str				=  num_hidden_layers
					_A :				Any				=  num_attention_heads
					_A :				List[Any]				=  intermediate_size
					_A :				Any				=  hidden_act
					_A :				int				=  hidden_dropout_prob
					_A :				Any				=  attention_probs_dropout_prob
					_A :				List[str]				=  max_position_embeddings
					_A :				List[Any]				=  initializer_range
					_A :				Optional[int]				=  None
					_A :				int				=  vocab_size - 1
					_A :				str				=  vocab_size - 1
					_A :				Optional[int]				=  vocab_size - 1




	def 				_lowerCamelCase				(					self			)       ->				List[str]:
					_A :				Tuple				=  ids_tensor([self.batch_size, self.seq_length]   ,     self.vocab_size			)

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

					_A :				Optional[Any]				=  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=__UpperCamelCase   ,     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 				_lowerCamelCase				(					self			)       ->				int:
					_A :				Optional[Any]				=  self.prepare_config_and_inputs()
					_A	,       _A	,       _A :				str				=  config_and_inputs
					_A :				List[Any]				=  {'''input_ids''': input_ids, '''attention_mask''': attention_mask}
					return config, inputs_dict




	def 				_lowerCamelCase				(					self			)       ->				List[Any]:
					_A	,       _A	,       _A :				Optional[Any]				=  self.prepare_config_and_inputs()

					_A :				Dict				=  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]			)
					_A :				Optional[Any]				=  ids_tensor([self.batch_size, self.seq_length]   ,     vocab_size=2			)

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




	def 				_lowerCamelCase				(					self   ,     UpperCAmelCase__   ,     UpperCAmelCase__   ,     UpperCAmelCase__   ,     UpperCAmelCase__			)       ->				List[str]:
					_A :				Optional[Any]				=  2_0
					_A :				Optional[Any]				=  model_class_name(__UpperCamelCase			)

					_A :				Tuple				=  model.init_cache(input_ids.shape[0]   ,     __UpperCamelCase			)
					_A :				Optional[Any]				=  jnp.ones((input_ids.shape[0], max_decoder_length)   ,     dtype='''i4'''			)

					_A :				str				=  jnp.broadcast_to(
					    jnp.arange(input_ids.shape[-1] - 1			)[None, :]   ,     (input_ids.shape[0], input_ids.shape[-1] - 1)			)
					_A :				List[Any]				=  model(
					    input_ids[:, :-1]   ,     attention_mask=__UpperCamelCase   ,     past_key_values=__UpperCamelCase   ,     position_ids=__UpperCamelCase   ,     )

					_A :				Dict				=  jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]   ,     dtype='''i4'''			)
					_A :				Union[str, Any]				=  model(
					    input_ids[:, -1:]   ,     attention_mask=__UpperCamelCase   ,     past_key_values=outputs_cache.past_key_values   ,     position_ids=__UpperCamelCase   ,     )

					_A :				int				=  model(__UpperCamelCase			)

					_A :				str				=  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 				_lowerCamelCase				(					self   ,     UpperCAmelCase__   ,     UpperCAmelCase__   ,     UpperCAmelCase__   ,     UpperCAmelCase__			)       ->				int:
					_A :				int				=  2_0
					_A :				Optional[int]				=  model_class_name(__UpperCamelCase			)

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

					_A :				Union[str, Any]				=  model.init_cache(input_ids.shape[0]   ,     __UpperCamelCase			)
					_A :				Union[str, Any]				=  jnp.broadcast_to(
					    jnp.arange(input_ids.shape[-1] - 1			)[None, :]   ,     (input_ids.shape[0], input_ids.shape[-1] - 1)			)

					_A :				Union[str, Any]				=  model(
					    input_ids[:, :-1]   ,     attention_mask=__UpperCamelCase   ,     past_key_values=__UpperCamelCase   ,     position_ids=__UpperCamelCase   ,     )
					_A :				Union[str, Any]				=  jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]   ,     dtype='''i4'''			)
					_A :				Any				=  model(
					    input_ids[:, -1:]   ,     past_key_values=outputs_cache.past_key_values   ,     attention_mask=__UpperCamelCase   ,     position_ids=__UpperCamelCase   ,     )

					_A :				Dict				=  model(__UpperCamelCase   ,     attention_mask=__UpperCamelCase			)

					_A :				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}"""			)



@require_flax
class  lowerCamelCase__				(						snake_case_  ,							snake_case_  ,							unittest.TestCase						):


	"""simple docstring"""





	__magic_name__							   =		(FlaxGPTaModel, FlaxGPTaLMHeadModel) if is_flax_available() else ()
	__magic_name__							   =		(FlaxGPTaLMHeadModel,) if is_flax_available() else ()




	def 				_lowerCamelCase				(					self			)       ->				str:
					_A :				List[str]				=  FlaxGPTaModelTester(self			)




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





					for model_class_name in self.all_model_classes:
									_A	,       _A	,       _A :				int				=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.check_use_cache_forward(__UpperCamelCase   ,     __UpperCamelCase   ,     __UpperCamelCase   ,     __UpperCamelCase			)




	def 				_lowerCamelCase				(					self			)       ->				Any:





					for model_class_name in self.all_model_classes:
									_A	,       _A	,       _A :				Any				=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.check_use_cache_forward_with_attn_mask(
									    __UpperCamelCase   ,     __UpperCamelCase   ,     __UpperCamelCase   ,     __UpperCamelCase			)




	@slow
	def 				_lowerCamelCase				(					self			)       ->				Any:
					_A :				int				=  GPTaTokenizer.from_pretrained('''gpt2'''   ,     pad_token='''</s>'''   ,     padding_side='''left'''			)
					_A :				Any				=  tokenizer(['''Hello this is a long string''', '''Hey''']   ,     return_tensors='''np'''   ,     padding=__UpperCamelCase   ,     truncation=__UpperCamelCase			)

					_A :				str				=  FlaxGPTaLMHeadModel.from_pretrained('''gpt2'''			)
					_A :				str				=  False
					_A :				Union[str, Any]				=  model.config.eos_token_id

					_A :				List[str]				=  jax.jit(model.generate			)

					_A :				Union[str, Any]				=  jit_generate(inputs['''input_ids''']   ,     attention_mask=inputs['''attention_mask''']			).sequences

					_A :				Union[str, Any]				=  tokenizer.batch_decode(__UpperCamelCase   ,     skip_special_tokens=__UpperCamelCase			)

					_A :				Any				=  [
					    '''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(__UpperCamelCase   ,     __UpperCamelCase			)




	@is_pt_flax_cross_test
	def 				_lowerCamelCase				(					self			)       ->				Optional[Any]:
					_A	,       _A :				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
													_A :				Union[str, Any]				=  self._prepare_for_class(__UpperCamelCase   ,     __UpperCamelCase			)
													_A :				Union[str, Any]				=  {k: torch.tensor(v.tolist()			) for k, v in prepared_inputs_dict.items()}

													# load corresponding PyTorch class
													_A :				int				=  model_class.__name__[4:]  # Skip the "Flax" at the beginning
													_A :				Union[str, Any]				=  getattr(__UpperCamelCase   ,     __UpperCamelCase			)

													_A	,       _A :				Any				=  pt_inputs['''input_ids'''].shape
													_A :				Dict				=  np.random.randint(0   ,     seq_length - 1   ,     size=(batch_size,)			)
													for batch_idx, start_index in enumerate(__UpperCamelCase			):
																	_A :				str				=  0
																	_A :				int				=  1
																	_A :				Union[str, Any]				=  0
																	_A :				Dict				=  1
													_A :				str				=  pt_model_class(__UpperCamelCase			).eval()
													_A :				int				=  model_class(__UpperCamelCase   ,     dtype=jnp.floataa			)

													_A :				Optional[Any]				=  convert_pytorch_state_dict_to_flax(pt_model.state_dict()   ,     __UpperCamelCase			)
													_A :				List[Any]				=  fx_state

													with torch.no_grad():
																	_A :				List[Any]				=  pt_model(**__UpperCamelCase			).to_tuple()

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

													with tempfile.TemporaryDirectory() as tmpdirname:
																	pt_model.save_pretrained(__UpperCamelCase			)
																	_A :				Union[str, Any]				=  model_class.from_pretrained(__UpperCamelCase   ,     from_pt=__UpperCamelCase			)

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




	@is_pt_flax_cross_test
	def 				_lowerCamelCase				(					self			)       ->				List[Any]:
					_A	,       _A :				int				=  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
													_A :				List[str]				=  self._prepare_for_class(__UpperCamelCase   ,     __UpperCamelCase			)
													_A :				Tuple				=  {k: torch.tensor(v.tolist()			) for k, v in prepared_inputs_dict.items()}

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

													_A :				Any				=  pt_model_class(__UpperCamelCase			).eval()
													_A :				List[str]				=  model_class(__UpperCamelCase   ,     dtype=jnp.floataa			)

													_A :				Dict				=  load_flax_weights_in_pytorch_model(__UpperCamelCase   ,     fx_model.params			)
													_A	,       _A :				Optional[int]				=  pt_inputs['''input_ids'''].shape
													_A :				str				=  np.random.randint(0   ,     seq_length - 1   ,     size=(batch_size,)			)
													for batch_idx, start_index in enumerate(__UpperCamelCase			):
																	_A :				List[Any]				=  0
																	_A :				List[str]				=  1
																	_A :				Optional[Any]				=  0
																	_A :				List[str]				=  1

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

													with torch.no_grad():
																	_A :				List[str]				=  pt_model(**__UpperCamelCase			).to_tuple()

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

													with tempfile.TemporaryDirectory() as tmpdirname:
																	fx_model.save_pretrained(__UpperCamelCase			)
																	_A :				List[str]				=  pt_model_class.from_pretrained(__UpperCamelCase   ,     from_flax=__UpperCamelCase			)

													with torch.no_grad():
																	_A :				List[Any]				=  pt_model_loaded(**__UpperCamelCase			).to_tuple()

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




	@slow
	def 				_lowerCamelCase				(					self			)       ->				int:





					for model_class_name in self.all_model_classes:
									_A :				List[str]				=  model_class_name.from_pretrained('''gpt2'''   ,     from_pt=__UpperCamelCase			)
									_A :				Any				=  model(np.ones((1, 1)			)			)
									self.assertIsNotNone(__UpperCamelCase			)



from hashlib import mda, shaaaa

A__							=				(shaaaa, mda)

class 					__UpperCamelCase					:







	def __init__( self:			Optional[int]	,			__UpperCamelCase:			int = 8   ):

						'''simple docstring'''





						__magic_name__				=     0b0
						__magic_name__				=     size







	def 						_SCREAMING_SNAKE_CASE				( self:			Tuple	,			__UpperCamelCase:			str   ):

						'''simple docstring'''





						__magic_name__				=     self.hash_(__UpperCamelCase   )
						self.bitarray |= h







	def 						_SCREAMING_SNAKE_CASE				( self:			List[str]	,			__UpperCamelCase:			str   ):

						'''simple docstring'''





						__magic_name__				=     self.hash_(__UpperCamelCase   )
						return (h & self.bitarray) == h







	def __contains__( self:			Optional[int]	,			__UpperCamelCase:			str   ):

						'''simple docstring'''





						return self.exists(__UpperCamelCase   )







	def 						_SCREAMING_SNAKE_CASE				( self:			int	,			__UpperCamelCase:			int   ):

						'''simple docstring'''





						__magic_name__				=     bin(__UpperCamelCase   )[2:]
						return res.zfill(self.size   )







	@property
	def 						_SCREAMING_SNAKE_CASE				( self:			str   ):

						'''simple docstring'''





						return self.format_bin(self.bitarray   )







	def 						_SCREAMING_SNAKE_CASE				( self:			str	,			__UpperCamelCase:			str   ):

						'''simple docstring'''





						__magic_name__				=     0b0
						for func in HASH_FUNCTIONS:
											__magic_name__				=     (
											    int.from_bytes(func(value.encode()   ).digest()	,			'little'   ) % self.size
											)
											res |= 2**position
						return res







	def 						_SCREAMING_SNAKE_CASE				( self:			Dict	,			__UpperCamelCase:			str   ):

						'''simple docstring'''





						return self.format_bin(self.hash_(__UpperCamelCase   )   )







	@property
	def 						_SCREAMING_SNAKE_CASE				( self:			Optional[int]   ):

						'''simple docstring'''





						__magic_name__				=     bin(self.bitarray   ).count('1'   )
						return (n_ones / self.size) ** len(__UpperCamelCase   )




