
'''simple docstring'''







from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


lowercase					:							Any   =      logging.get_logger(__name__)







def        SCREAMING_SNAKE_CASE__			(     __A			) ->			List[int]:
	if isinstance(__A    ,       np.ndarray			):
		return list(tensor.shape			)

	_snake_case     		=	tf.shape(__A			)

	if tensor.shape == tf.TensorShape(__A			):
		return dynamic

	_snake_case     		=	tensor.shape.as_list()

	return [dynamic[i] if s is None else s for i, s in enumerate(__A			)]







def        SCREAMING_SNAKE_CASE__			(     __A    ,       __A = None    ,       __A = None			) ->			tf.Tensor:
	return tf.nn.softmax(logits=logits + 1e-9    ,       axis=__A    ,       name=__A			)







def        SCREAMING_SNAKE_CASE__			(     __A    ,       __A    ,       __A    ,       __A=1e-5    ,       __A=-1			) ->			List[str]:
	# This is a very simplified functional layernorm, designed to duplicate
	# the functionality of PyTorch nn.functional.layer_norm when this is needed to port
	# models in Transformers.

	if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(__A    ,       __A			):
		raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.'			)

	# Get mean and variance on the axis to be normalized
	_snake_case		,				_snake_case     		=	tf.nn.moments(__A    ,       axes=[axis]    ,       keepdims=__A			)

	if axis != -1:
		# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
		# on every dimension except axis
		_snake_case     		=	[1] * inputs.shape.rank
		_snake_case     		=	shape_list(__A			)[axis]
		_snake_case     		=	tf.reshape(__A    ,       __A			)
		_snake_case     		=	tf.reshape(__A    ,       __A			)

	# Compute layer normalization using the batch_normalization
	# function.
	_snake_case     		=	tf.nn.batch_normalization(
	    __A    ,       __A    ,       __A    ,       offset=__A    ,       scale=__A    ,       variance_epsilon=__A    ,       )
	return outputs







def        SCREAMING_SNAKE_CASE__			(     __A    ,       __A=0    ,       __A=-1			) ->			Any:
	# Replicates the behavior of torch.flatten in TF

	# If end_dim or start_dim is negative, count them from the end
	if end_dim < 0:
		end_dim += input.shape.rank
	if start_dim < 0:
		start_dim += input.shape.rank

	if start_dim == end_dim:
		return input

	_snake_case     		=	tf.shape(__A			)
	_snake_case     		=	tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]			)
	_snake_case     		=	tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]    ,       axis=0			)
	return tf.reshape(__A    ,       __A			)







def        SCREAMING_SNAKE_CASE__			(     __A			) ->			tf.Tensor:
	if not isinstance(__A    ,       tf.Tensor			):
		_snake_case     		=	tf.convert_to_tensor(__A			)  # Catches stray NumPy inputs
	if encoder_attention_mask.shape.rank == 3:
		_snake_case     		=	encoder_attention_mask[:, None, :, :]
	if encoder_attention_mask.shape.rank == 2:
		_snake_case     		=	encoder_attention_mask[:, None, None, :]
	# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
	# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
	# /transformer/transformer_layers.py#L270
	# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
	# encoder_extended_attention_mask.transpose(-1, -2))
	_snake_case     		=	(
	    tf.cast(1    ,       encoder_attention_mask.dtype			) - encoder_extended_attention_mask
	) * encoder_extended_attention_mask.dtype.min

	return encoder_extended_attention_mask







def        SCREAMING_SNAKE_CASE__			(     __A    ,       __A    ,       __A = "input_ids"			) ->			None:
	tf.debugging.assert_less(
	    __A    ,       tf.cast(__A    ,       dtype=tensor.dtype			)    ,       message=(
	        F'The maximum value of {tensor_name} ({tf.math.reduce_max(__A			)}) must be smaller than the embedding '
	        F'layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.'
	    )    ,       )







def        SCREAMING_SNAKE_CASE__			(     __A    ,       __A    ,       __A			) ->			Any:
	_snake_case     		=	64_512
	# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
	# because in that case even chunking the array would not make the saving
	# possible.
	_snake_case     		=	[x for x in data if len(__A			) > HDF5_OBJECT_HEADER_LIMIT]

	# Expecting this to never be true.
	if bad_attributes:
		raise RuntimeError(
		    'The following attributes cannot be saved to HDF5 file because '
		    F'they are larger than {HDF5_OBJECT_HEADER_LIMIT} '
		    F'bytes: {bad_attributes}'			)

	_snake_case     		=	np.asarray(__A			)

	_snake_case     		=	1
	_snake_case     		=	np.array_split(__A    ,       __A			)

	# This will never loop forever thanks to the test above.
	while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data			):
		num_chunks += 1
		_snake_case     		=	np.array_split(__A    ,       __A			)

	if num_chunks > 1:
		for chunk_id, chunk_data in enumerate(__A			):
			_snake_case     		=	chunk_data
	else:
		_snake_case     		=	data







def        SCREAMING_SNAKE_CASE__			(     __A    ,       __A			) ->			List[str]:
	if name in group.attrs:
		_snake_case     		=	[n.decode('utf8'			) if hasattr(__A    ,       'decode'			) else n for n in group.attrs[name]]
	else:
		_snake_case     		=	[]
		_snake_case     		=	0
		while "%s%d" % (name, chunk_id) in group.attrs:
			data.extend(
			    [n.decode('utf8'			) if hasattr(__A    ,       'decode'			) else n for n in group.attrs['%s%d' % (name, chunk_id)]]			)
			chunk_id += 1
	return data







def        SCREAMING_SNAKE_CASE__			(     __A			) ->			Any:

	def _expand_single_ad_tensor(__A			):
		if isinstance(__A    ,       tf.Tensor			) and t.shape.rank == 1:
			return tf.expand_dims(__A    ,       axis=-1			)
		return t

	return tf.nest.map_structure(_expand_single_ad_tensor    ,       __A			)



'''simple docstring'''







import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
					    OpenAIGPTConfig,
					    OpenAIGPTDoubleHeadsModel,
					    OpenAIGPTForSequenceClassification,
					    OpenAIGPTLMHeadModel,
					    OpenAIGPTModel,
					)


class 		__UpperCAmelCase   :


							def __init__( self					,     lowerCAmelCase_					,     lowerCAmelCase_=13					,     lowerCAmelCase_=7					,     lowerCAmelCase_=True					,     lowerCAmelCase_=True					,     lowerCAmelCase_=True					,     lowerCAmelCase_=99					,     lowerCAmelCase_=32					,     lowerCAmelCase_=5					,     lowerCAmelCase_=4					,     lowerCAmelCase_=37					,     lowerCAmelCase_="gelu"					,     lowerCAmelCase_=0.1					,     lowerCAmelCase_=0.1					,     lowerCAmelCase_=5_12					,     lowerCAmelCase_=16					,     lowerCAmelCase_=2					,     lowerCAmelCase_=0.02					,     lowerCAmelCase_=3					,     lowerCAmelCase_=4					,     lowerCAmelCase_=None					,     ):





								"""simple docstring"""






								_snake_case     		=	parent
								_snake_case     		=	batch_size
								_snake_case     		=	seq_length
								_snake_case     		=	is_training
								_snake_case     		=	use_token_type_ids
								_snake_case     		=	use_labels
								_snake_case     		=	vocab_size
								_snake_case     		=	hidden_size
								_snake_case     		=	num_hidden_layers
								_snake_case     		=	num_attention_heads
								_snake_case     		=	intermediate_size
								_snake_case     		=	hidden_act
								_snake_case     		=	hidden_dropout_prob
								_snake_case     		=	attention_probs_dropout_prob
								_snake_case     		=	max_position_embeddings
								_snake_case     		=	type_vocab_size
								_snake_case     		=	type_sequence_label_size
								_snake_case     		=	initializer_range
								_snake_case     		=	num_labels
								_snake_case     		=	num_choices
								_snake_case     		=	scope
								_snake_case     		=	self.vocab_size - 1


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






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

								_snake_case     		=	None
								if self.use_token_type_ids:
									_snake_case     		=	ids_tensor([self.batch_size, self.seq_length]					,     self.type_vocab_size						)

								_snake_case     		=	None
								_snake_case     		=	None
								_snake_case     		=	None
								if self.use_labels:
									_snake_case     		=	ids_tensor([self.batch_size]					,     self.type_sequence_label_size						)
									_snake_case     		=	ids_tensor([self.batch_size, self.seq_length]					,     self.num_labels						)
									_snake_case     		=	ids_tensor([self.batch_size]					,     self.num_choices						)

								_snake_case     		=	OpenAIGPTConfig(
								    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					,     pad_token_id=self.pad_token_id					,     )

								_snake_case     		=	ids_tensor([self.num_hidden_layers, self.num_attention_heads]					,     2						)

								return (
								    config,
								    input_ids,
								    head_mask,
								    token_type_ids,
								    sequence_labels,
								    token_labels,
								    choice_labels,
								)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTModel(config=lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     head_mask=lowerCAmelCase_						)
								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_						)
								_snake_case     		=	model(lowerCAmelCase_						)

								self.parent.assertEqual(result.last_hidden_state.shape					,     (self.batch_size, self.seq_length, self.hidden_size)						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTLMHeadModel(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     labels=lowerCAmelCase_						)
								self.parent.assertEqual(result.loss.shape					,     ()						)
								self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.seq_length, self.vocab_size)						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTDoubleHeadsModel(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     labels=lowerCAmelCase_						)
								self.parent.assertEqual(result.loss.shape					,     ()						)
								self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.seq_length, self.vocab_size)						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	self.num_labels
								_snake_case     		=	OpenAIGPTForSequenceClassification(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	ids_tensor([self.batch_size]					,     self.type_sequence_label_size						)
								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     labels=lowerCAmelCase_						)
								self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.num_labels)						)




							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.prepare_config_and_inputs()
								(
								    (
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				
								)     		=	config_and_inputs
								_snake_case     		=	{
								    'input_ids': input_ids,
								    'token_type_ids': token_type_ids,
								    'head_mask': head_mask,
								}

								return config, inputs_dict


@require_torch
class 		__UpperCAmelCase   (      _lowerCamelCase		,     _lowerCamelCase		,     _lowerCamelCase		,     unittest.TestCase		):
							__lowercase   	= (
							    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
							    if is_torch_available()
							    else ()
							)
							__lowercase   	= (
							    (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
							)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
							__lowercase   	= (
							    {
							        """feature-extraction""": OpenAIGPTModel,
							        """text-classification""": OpenAIGPTForSequenceClassification,
							        """text-generation""": OpenAIGPTLMHeadModel,
							        """zero-shot""": OpenAIGPTForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_						):





								"""simple docstring"""






								if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
									# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
									# `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
									# tiny config could not be created.
									return True

								return False


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





								"""simple docstring"""






								_snake_case     		=	super()._prepare_for_class(lowerCAmelCase_					,     lowerCAmelCase_					,     return_labels=lowerCAmelCase_						)

								if return_labels:
									if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
										_snake_case     		=	torch.zeros(
										    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)					,     dtype=torch.long					,     device=lowerCAmelCase_					,     )
										_snake_case     		=	inputs_dict['labels']
										_snake_case     		=	inputs_dict['labels']
										_snake_case     		=	torch.zeros(
										    (self.model_tester.batch_size, self.model_tester.num_choices)					,     dtype=torch.long					,     device=lowerCAmelCase_					,     )
										_snake_case     		=	torch.zeros(
										    self.model_tester.batch_size					,     dtype=torch.long					,     device=lowerCAmelCase_						)
								return inputs_dict


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTModelTester(self						)
								_snake_case     		=	ConfigTester(self					,     config_class=lowerCAmelCase_					,     n_embd=37						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								self.config_tester.run_common_tests()


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_openai_gpt_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_lm_head_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_double_lm_head_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowerCAmelCase_						)




							@slow
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									_snake_case     		=	OpenAIGPTModel.from_pretrained(lowerCAmelCase_						)
									self.assertIsNotNone(lowerCAmelCase_						)


@require_torch
class 		__UpperCAmelCase   (      unittest.TestCase		):


							@slow
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTLMHeadModel.from_pretrained('openai-gpt'						)
								model.to(lowerCAmelCase_						)
								_snake_case     		=	torch.tensor([[4_81, 47_35, 5_44]]					,     dtype=torch.long					,     device=lowerCAmelCase_						)  # the president is
								_snake_case     		=	[
								    4_81,
								    47_35,
								    5_44,
								    2_46,
								    9_63,
								    8_70,
								    7_62,
								    2_39,
								    2_44,
								    4_04_77,
								    2_44,
								    2_49,
								    7_19,
								    8_81,
								    4_87,
								    5_44,
								    2_40,
								    2_44,
								    6_03,
								    4_81,
								]  # the president is a very good man. " \n " i\'m sure he is, " said the

								_snake_case     		=	model.generate(lowerCAmelCase_					,     do_sample=lowerCAmelCase_						)
								self.assertListEqual(output_ids[0].tolist()					,     lowerCAmelCase_						)

