





"""simple docstring"""




from __future__ import annotations

import unittest

from transformers import OpenAIGPTConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers.models.openai.modeling_tf_openai import (
						    TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
						    TFOpenAIGPTDoubleHeadsModel,
						    TFOpenAIGPTForSequenceClassification,
						    TFOpenAIGPTLMHeadModel,
						    TFOpenAIGPTModel,
						)




class 					_a		:






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




										'''simple docstring'''



										_UpperCamelCase     :   Any      =       parent
										_UpperCamelCase     :   str      =       1_3
										_UpperCamelCase     :   Optional[int]      =       7
										_UpperCamelCase     :   Tuple      =       True
										_UpperCamelCase     :   Dict      =       True
										_UpperCamelCase     :   int      =       True
										_UpperCamelCase     :   Any      =       True
										_UpperCamelCase     :   Union[str, Any]      =       True
										_UpperCamelCase     :   Union[str, Any]      =       9_9
										_UpperCamelCase     :   str      =       3_2
										_UpperCamelCase     :   Any      =       2
										_UpperCamelCase     :   Dict      =       4
										_UpperCamelCase     :   Union[str, Any]      =       3_7
										_UpperCamelCase     :   Any      =       '''gelu'''
										_UpperCamelCase     :   List[str]      =       0.1
										_UpperCamelCase     :   Dict      =       0.1
										_UpperCamelCase     :   List[Any]      =       5_1_2
										_UpperCamelCase     :   Dict      =       1_6
										_UpperCamelCase     :   str      =       2
										_UpperCamelCase     :   Any      =       0.02
										_UpperCamelCase     :   List[Any]      =       3
										_UpperCamelCase     :   List[str]      =       4
										_UpperCamelCase     :   Union[str, Any]      =       None
										_UpperCamelCase     :   Any      =       self.vocab_size - 1






				def 							snake_case      (					self						:       Union[str, Any]				)      -> Tuple:




										'''simple docstring'''



										_UpperCamelCase     :   Any      =       ids_tensor([self.batch_size, self.seq_length],					self.vocab_size				)

										_UpperCamelCase     :   Any      =       None
										if self.use_input_mask:
																_UpperCamelCase     :   List[Any]      =       random_attention_mask([self.batch_size, self.seq_length]				)

										_UpperCamelCase     :   int      =       None
										if self.use_token_type_ids:
																_UpperCamelCase     :   Union[str, Any]      =       ids_tensor([self.batch_size, self.seq_length],					self.type_vocab_size				)

										_UpperCamelCase     :   Union[str, Any]      =       None
										if self.use_mc_token_ids:
																_UpperCamelCase     :   Optional[Any]      =       ids_tensor([self.batch_size, self.num_choices],					self.seq_length				)

										_UpperCamelCase     :   int      =       None
										_UpperCamelCase     :   Optional[Any]      =       None
										_UpperCamelCase     :   str      =       None
										if self.use_labels:
																_UpperCamelCase     :   str      =       ids_tensor([self.batch_size],					self.type_sequence_label_size				)
																_UpperCamelCase     :   Tuple      =       ids_tensor([self.batch_size, self.seq_length],					self.num_labels				)
																_UpperCamelCase     :   str      =       ids_tensor([self.batch_size],					self.num_choices				)

										_UpperCamelCase     :   List[str]      =       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,					)

										_UpperCamelCase     :   int      =       ids_tensor([self.num_hidden_layers, self.num_attention_heads],					2				)

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






				def 							snake_case      (					self						:       Any,					lowerCAmelCase__						:       Any,					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       List[Any],					lowerCAmelCase__						:       Any,					*lowerCAmelCase__						:       Dict				)      -> Any:




										'''simple docstring'''



										_UpperCamelCase     :   Dict      =       TFOpenAIGPTModel(config=lowerCAmelCase__				)
										_UpperCamelCase     :   Any      =       {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
										_UpperCamelCase     :   Optional[int]      =       model(lowerCAmelCase__				)

										_UpperCamelCase     :   str      =       [input_ids, input_mask]
										_UpperCamelCase     :   Union[str, Any]      =       model(lowerCAmelCase__				)

										_UpperCamelCase     :   Any      =       model(lowerCAmelCase__				)

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






				def 							snake_case      (					self						:       Any,					lowerCAmelCase__						:       List[Any],					lowerCAmelCase__						:       str,					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       int,					lowerCAmelCase__						:       List[str],					*lowerCAmelCase__						:       List[str]				)      -> Optional[Any]:




										'''simple docstring'''



										_UpperCamelCase     :   int      =       TFOpenAIGPTLMHeadModel(config=lowerCAmelCase__				)
										_UpperCamelCase     :   Dict      =       {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
										_UpperCamelCase     :   Any      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.seq_length, self.vocab_size)				)






				def 							snake_case      (					self						:       Tuple,					lowerCAmelCase__						:       Optional[int],					lowerCAmelCase__						:       List[Any],					lowerCAmelCase__						:       int,					lowerCAmelCase__						:       int,					lowerCAmelCase__						:       Tuple,					lowerCAmelCase__						:       Union[str, Any],					*lowerCAmelCase__						:       int				)      -> List[Any]:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[int]      =       TFOpenAIGPTDoubleHeadsModel(config=lowerCAmelCase__				)

										_UpperCamelCase     :   Any      =       tf.tile(tf.expand_dims(lowerCAmelCase__,					1				),					(1, self.num_choices, 1)				)
										_UpperCamelCase     :   Union[str, Any]      =       tf.tile(tf.expand_dims(lowerCAmelCase__,					1				),					(1, self.num_choices, 1)				)
										_UpperCamelCase     :   Any      =       tf.tile(tf.expand_dims(lowerCAmelCase__,					1				),					(1, self.num_choices, 1)				)

										_UpperCamelCase     :   int      =       {
										    '''input_ids''': multiple_choice_inputs_ids,
										    '''mc_token_ids''': mc_token_ids,
										    '''attention_mask''': multiple_choice_input_mask,
										    '''token_type_ids''': multiple_choice_token_type_ids,
										}
										_UpperCamelCase     :   List[str]      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(
										    result.logits.shape,					(self.batch_size, self.num_choices, self.seq_length, self.vocab_size)				)
										self.parent.assertEqual(result.mc_logits.shape,					(self.batch_size, self.num_choices)				)






				def 							snake_case      (					self						:       Any,					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Union[str, Any],					*lowerCAmelCase__						:       Tuple				)      -> str:




										'''simple docstring'''



										_UpperCamelCase     :   Tuple      =       self.num_labels
										_UpperCamelCase     :   int      =       ids_tensor([self.batch_size],					self.type_sequence_label_size				)
										_UpperCamelCase     :   List[Any]      =       {
										    '''input_ids''': input_ids,
										    '''attention_mask''': input_mask,
										    '''token_type_ids''': token_type_ids,
										    '''labels''': sequence_labels,
										}
										_UpperCamelCase     :   int      =       TFOpenAIGPTForSequenceClassification(lowerCAmelCase__				)
										_UpperCamelCase     :   List[Any]      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.num_labels)				)






				def 							snake_case      (					self						:       Optional[int]				)      -> List[Any]:




										'''simple docstring'''



										_UpperCamelCase     :   int      =       self.prepare_config_and_inputs()

										(
										    (
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				(
										    _UpperCamelCase
										)  ,				
										)     :   List[Any]      =       config_and_inputs

										_UpperCamelCase     :   Tuple      =       {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
										return config, inputs_dict




@require_tf
class 					_a		( _lowerCAmelCase      ,							_lowerCAmelCase      ,							unittest.TestCase							):
				UpperCamelCase								=       (
				    (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, TFOpenAIGPTDoubleHeadsModel, TFOpenAIGPTForSequenceClassification)
				    if is_tf_available()
				    else ()
				)
				UpperCamelCase								=       (
				    (TFOpenAIGPTLMHeadModel,) if is_tf_available() else ()
				)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
				UpperCamelCase								=       (
				    {
				        '''feature-extraction''': TFOpenAIGPTModel,
				        '''text-classification''': TFOpenAIGPTForSequenceClassification,
				        '''text-generation''': TFOpenAIGPTLMHeadModel,
				        '''zero-shot''': TFOpenAIGPTForSequenceClassification,
				    }
				    if is_tf_available()
				    else {}
				)
				UpperCamelCase								=       False
				UpperCamelCase								=       False






				def 							snake_case      (					self						:       Optional[int],					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       List[Any],					lowerCAmelCase__						:       Any,					lowerCAmelCase__						:       Tuple				)      -> Tuple:




										'''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 							snake_case      (					self						:       Tuple				)      -> Dict:




										'''simple docstring'''



										_UpperCamelCase     :   List[Any]      =       TFOpenAIGPTModelTester(self				)
										_UpperCamelCase     :   Any      =       ConfigTester(self,					config_class=lowerCAmelCase__,					n_embd=3_7				)






				def 							snake_case      (					self						:       int				)      -> Tuple:




										'''simple docstring'''



										self.config_tester.run_common_tests()






				def 							snake_case      (					self						:       Tuple				)      -> int:




										'''simple docstring'''



										_UpperCamelCase     :   int      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_openai_gpt_model(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       str				)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   int      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_openai_gpt_lm_head(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       str				)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_openai_gpt_double_head(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       List[str]				)      -> Union[str, Any]:




										'''simple docstring'''



										_UpperCamelCase     :   List[Any]      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowerCAmelCase__				)






				@slow
				def 							snake_case      (					self						:       Union[str, Any]				)      -> Any:




										'''simple docstring'''



										for model_name in TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCamelCase     :   str      =       TFOpenAIGPTModel.from_pretrained(lowerCAmelCase__				)
																self.assertIsNotNone(lowerCAmelCase__				)




@require_tf
class 					_a		( unittest.TestCase							):






				@slow
				def 							snake_case      (					self						:       Optional[Any]				)      -> List[Any]:




										'''simple docstring'''



										_UpperCamelCase     :   Any      =       TFOpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''				)
										_UpperCamelCase     :   Tuple      =       tf.convert_to_tensor([[4_8_1, 4_7_3_5, 5_4_4]],					dtype=tf.intaa				)  # the president is
										_UpperCamelCase     :   str      =       [
										    4_8_1,
										    4_7_3_5,
										    5_4_4,
										    2_4_6,
										    9_6_3,
										    8_7_0,
										    7_6_2,
										    2_3_9,
										    2_4_4,
										    4_0_4_7_7,
										    2_4_4,
										    2_4_9,
										    7_1_9,
										    8_8_1,
										    4_8_7,
										    5_4_4,
										    2_4_0,
										    2_4_4,
										    6_0_3,
										    4_8_1,
										]  # the president is a very good man. " \n " i\'m sure he is, " said the

										_UpperCamelCase     :   Any      =       model.generate(lowerCAmelCase__,					do_sample=lowerCAmelCase__				)
										self.assertListEqual(output_ids[0].numpy().tolist(),					lowerCAmelCase__				)









from dataclasses import dataclass
from typing import Optional, Tuple, Union

import flax
import jax.numpy as jnp
from scipy import integrate

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils_flax import (
    CommonSchedulerState,
    FlaxKarrasDiffusionSchedulers,
    FlaxSchedulerMixin,
    FlaxSchedulerOutput,
    broadcast_to_shape_from_left,
)

@flax.struct.dataclass
class 			_lowerCamelCase    :

      """simple docstring"""

      lowerCAmelCase__      :			CommonSchedulerState

      # setable values
      lowerCAmelCase__      :			jnp.ndarray
      lowerCAmelCase__      :			jnp.ndarray
      lowerCAmelCase__      :			jnp.ndarray
      lowerCAmelCase__      :			Optional[int]     =       None

      # running values
      lowerCAmelCase__      :			Optional[jnp.ndarray]     =       None







      @classmethod
      def    snake_case						(  cls       :			str			,							snake_case       :			CommonSchedulerState			,							snake_case       :			jnp.ndarray			,							snake_case       :			jnp.ndarray			,							snake_case       :			jnp.ndarray					):
          return cls(common=snake_case			,							init_noise_sigma=snake_case			,							timesteps=snake_case			,							sigmas=snake_case					)







@dataclass
class 			_lowerCamelCase    (      _SCREAMING_SNAKE_CASE ):

      """simple docstring"""

      lowerCAmelCase__      :			LMSDiscreteSchedulerState







class 			_lowerCamelCase    (      _SCREAMING_SNAKE_CASE				,      _SCREAMING_SNAKE_CASE ):

      """simple docstring"""

      lowerCAmelCase__      :			List[Any]     =       [e.name for e in FlaxKarrasDiffusionSchedulers]

      lowerCAmelCase__      :			jnp.dtype







      @property
      def    snake_case						(  self       :			Any					):
          return True







      @register_to_config
      def __init__(  self       :			Union[str, Any]			,							snake_case       :			int = 1000			,							snake_case       :			float = 0.00_01			,							snake_case       :			float = 0.02			,							snake_case       :			str = "linear"			,							snake_case       :			Optional[jnp.ndarray] = None			,							snake_case       :			str = "epsilon"			,							snake_case       :			jnp.dtype = jnp.floataa			,							):
          __UpperCamelCase			=    dtype







      def    snake_case						(  self       :			int			,							snake_case       :			Optional[CommonSchedulerState] = None					):
          if common is None:
              __UpperCamelCase			=    CommonSchedulerState.create(self					)

          __UpperCamelCase			=    jnp.arange(0			,							self.config.num_train_timesteps					).round()[::-1]
          __UpperCamelCase			=    ((1 - common.alphas_cumprod) / common.alphas_cumprod) ** 0.5

          # standard deviation of the initial noise distribution
          __UpperCamelCase			=    sigmas.max()

          return LMSDiscreteSchedulerState.create(
              common=snake_case			,							init_noise_sigma=snake_case			,							timesteps=snake_case			,							sigmas=snake_case			,							)







      def    snake_case						(  self       :			str			,							snake_case       :			LMSDiscreteSchedulerState			,							snake_case       :			jnp.ndarray			,							snake_case       :			int					):
          ((__UpperCamelCase)		,   )			=    jnp.where(state.timesteps == timestep			,							size=1					)
          __UpperCamelCase			=    step_index[0]

          __UpperCamelCase			=    state.sigmas[step_index]
          __UpperCamelCase			=    sample / ((sigma**2 + 1) ** 0.5)
          return sample







      def    snake_case						(  self       :			Optional[Any]			,							snake_case       :			LMSDiscreteSchedulerState			,							snake_case       :			str			,							snake_case       :			Tuple			,							snake_case       :			int					):

          def lms_derivative(snake_case       :			int					):
              __UpperCamelCase			=    1.0
              for k in range(snake_case					):
                  if current_order == k:
                      continue
                  prod *= (tau - state.sigmas[t - k]) / (state.sigmas[t - current_order] - state.sigmas[t - k])
              return prod

          __UpperCamelCase			=    integrate.quad(snake_case			,							state.sigmas[t]			,							state.sigmas[t + 1]			,							epsrel=1E-4					)[0]

          return integrated_coeff







      def    snake_case						(  self       :			int			,							snake_case       :			LMSDiscreteSchedulerState			,							snake_case       :			int			,							snake_case       :			Tuple = ()					):
          __UpperCamelCase			=    jnp.linspace(self.config.num_train_timesteps - 1			,							0			,							snake_case			,							dtype=self.dtype					)

          __UpperCamelCase			=    jnp.floor(snake_case					).astype(jnp.intaa					)
          __UpperCamelCase			=    jnp.ceil(snake_case					).astype(jnp.intaa					)

          __UpperCamelCase			=    jnp.mod(snake_case			,							1.0					)

          __UpperCamelCase			=    ((1 - state.common.alphas_cumprod) / state.common.alphas_cumprod) ** 0.5
          __UpperCamelCase			=    (1 - frac) * sigmas[low_idx] + frac * sigmas[high_idx]
          __UpperCamelCase			=    jnp.concatenate([sigmas, jnp.array([0.0]			,							dtype=self.dtype					)]					)

          __UpperCamelCase			=    timesteps.astype(jnp.intaa					)

          # initial running values
          __UpperCamelCase			=    jnp.zeros((0,) + shape			,							dtype=self.dtype					)

          return state.replace(
              timesteps=snake_case			,							sigmas=snake_case			,							num_inference_steps=snake_case			,							derivatives=snake_case			,							)







      def    snake_case						(  self       :			Tuple			,							snake_case       :			LMSDiscreteSchedulerState			,							snake_case       :			jnp.ndarray			,							snake_case       :			int			,							snake_case       :			jnp.ndarray			,							snake_case       :			int = 4			,							snake_case       :			bool = True			,							):
          if state.num_inference_steps is None:
              raise ValueError(
                  '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler'''					)

          __UpperCamelCase			=    state.sigmas[timestep]

          # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
          if self.config.prediction_type == "epsilon":
              __UpperCamelCase			=    sample - sigma * model_output
          elif self.config.prediction_type == "v_prediction":
              # * c_out + input * c_skip
              __UpperCamelCase			=    model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
          else:
              raise ValueError(
                  F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"					)

          # 2. Convert to an ODE derivative
          __UpperCamelCase			=    (sample - pred_original_sample) / sigma
          __UpperCamelCase			=    state.replace(derivatives=jnp.append(state.derivatives			,							snake_case					)					)
          if len(state.derivatives					) > order:
              __UpperCamelCase			=    state.replace(derivatives=jnp.delete(state.derivatives			,							0					)					)

          # 3. Compute linear multistep coefficients
          __UpperCamelCase			=    min(timestep + 1			,							snake_case					)
          __UpperCamelCase			=    [self.get_lms_coefficient(snake_case			,							snake_case			,							snake_case			,							snake_case					) for curr_order in range(snake_case					)]

          # 4. Compute previous sample based on the derivatives path
          __UpperCamelCase			=    sample + sum(
              coeff * derivative for coeff, derivative in zip(snake_case			,							reversed(state.derivatives					)					)					)

          if not return_dict:
              return (prev_sample, state)

          return FlaxLMSSchedulerOutput(prev_sample=snake_case			,							state=snake_case					)







      def    snake_case						(  self       :			Dict			,							snake_case       :			LMSDiscreteSchedulerState			,							snake_case       :			jnp.ndarray			,							snake_case       :			jnp.ndarray			,							snake_case       :			jnp.ndarray			,							):
          __UpperCamelCase			=    state.sigmas[timesteps].flatten()
          __UpperCamelCase			=    broadcast_to_shape_from_left(snake_case			,							noise.shape					)

          __UpperCamelCase			=    original_samples + noise * sigma

          return noisy_samples







      def __len__(  self       :			Optional[Any]					):
          return self.config.num_train_timesteps






