

from __future__ import annotations

import unittest

from transformers import FunnelConfig, is_tf_available
from transformers.testing_utils import require_tf

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 import (
           TFFunnelBaseModel,
           TFFunnelForMaskedLM,
           TFFunnelForMultipleChoice,
           TFFunnelForPreTraining,
           TFFunnelForQuestionAnswering,
           TFFunnelForSequenceClassification,
           TFFunnelForTokenClassification,
           TFFunnelModel,
       )



class       __snake_case  :

  def __init__(					self						,		_A						,		_A=13						,		_A=7						,		_A=True						,		_A=True						,		_A=True						,		_A=True						,		_A=99						,		_A=[1, 1, 2]						,		_A=1						,		_A=32						,		_A=4						,		_A=8						,		_A=37						,		_A="gelu_new"						,		_A=0.1						,		_A=0.1						,		_A=0.0						,		_A=512						,		_A=3						,		_A=0.0_2						,		_A=3						,		_A=4						,		_A=None						,		_A=False						,		):
      SCREAMING_SNAKE_CASE_									=						parent
      SCREAMING_SNAKE_CASE_									=						batch_size
      SCREAMING_SNAKE_CASE_									=						seq_length
      SCREAMING_SNAKE_CASE_									=						is_training
      SCREAMING_SNAKE_CASE_									=						use_input_mask
      SCREAMING_SNAKE_CASE_									=						use_token_type_ids
      SCREAMING_SNAKE_CASE_									=						use_labels
      SCREAMING_SNAKE_CASE_									=						vocab_size
      SCREAMING_SNAKE_CASE_									=						block_sizes
      SCREAMING_SNAKE_CASE_									=						num_decoder_layers
      SCREAMING_SNAKE_CASE_									=						d_model
      SCREAMING_SNAKE_CASE_									=						n_head
      SCREAMING_SNAKE_CASE_									=						d_head
      SCREAMING_SNAKE_CASE_									=						d_inner
      SCREAMING_SNAKE_CASE_									=						hidden_act
      SCREAMING_SNAKE_CASE_									=						hidden_dropout
      SCREAMING_SNAKE_CASE_									=						attention_dropout
      SCREAMING_SNAKE_CASE_									=						activation_dropout
      SCREAMING_SNAKE_CASE_									=						max_position_embeddings
      SCREAMING_SNAKE_CASE_									=						type_vocab_size
      SCREAMING_SNAKE_CASE_									=						2
      SCREAMING_SNAKE_CASE_									=						num_labels
      SCREAMING_SNAKE_CASE_									=						num_choices
      SCREAMING_SNAKE_CASE_									=						scope
      SCREAMING_SNAKE_CASE_									=						initializer_std

      # Used in the tests to check the size of the first attention layer
      SCREAMING_SNAKE_CASE_									=						n_head
      # Used in the tests to check the size of the first hidden state
      SCREAMING_SNAKE_CASE_									=						self.d_model
      # Used in the tests to check the number of output hidden states/attentions
      SCREAMING_SNAKE_CASE_									=						sum(self.block_sizes) + (0 if base else self.num_decoder_layers)
      # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
      # the last hidden state of the first block (which is the first hidden state of the decoder).
      if not base:
          SCREAMING_SNAKE_CASE_									=						self.num_hidden_layers + 2

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						ids_tensor([self.batch_size, self.seq_length]						,		self.vocab_size)

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

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

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

      SCREAMING_SNAKE_CASE_									=						FunnelConfig(
          vocab_size=self.vocab_size						,		block_sizes=self.block_sizes						,		num_decoder_layers=self.num_decoder_layers						,		d_model=self.d_model						,		n_head=self.n_head						,		d_head=self.d_head						,		d_inner=self.d_inner						,		hidden_act=self.hidden_act						,		hidden_dropout=self.hidden_dropout						,		attention_dropout=self.attention_dropout						,		activation_dropout=self.activation_dropout						,		max_position_embeddings=self.max_position_embeddings						,		type_vocab_size=self.type_vocab_size						,		initializer_std=self.initializer_std						,		)

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

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		):
      SCREAMING_SNAKE_CASE_									=						TFFunnelModel(config=_A)
      SCREAMING_SNAKE_CASE_									=						{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      SCREAMING_SNAKE_CASE_									=						model(_A)

      SCREAMING_SNAKE_CASE_									=						[input_ids, input_mask]
      SCREAMING_SNAKE_CASE_									=						model(_A)

      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.last_hidden_state.shape						,		(self.batch_size, self.seq_length, self.d_model))

      SCREAMING_SNAKE_CASE_									=						False
      SCREAMING_SNAKE_CASE_									=						TFFunnelModel(config=_A)
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.last_hidden_state.shape						,		(self.batch_size, self.seq_length, self.d_model))

      SCREAMING_SNAKE_CASE_									=						False
      SCREAMING_SNAKE_CASE_									=						TFFunnelModel(config=_A)
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.last_hidden_state.shape						,		(self.batch_size, self.seq_length, self.d_model))

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		):
      SCREAMING_SNAKE_CASE_									=						TFFunnelBaseModel(config=_A)
      SCREAMING_SNAKE_CASE_									=						{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      SCREAMING_SNAKE_CASE_									=						model(_A)

      SCREAMING_SNAKE_CASE_									=						[input_ids, input_mask]
      SCREAMING_SNAKE_CASE_									=						model(_A)

      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.last_hidden_state.shape						,		(self.batch_size, 2, self.d_model))

      SCREAMING_SNAKE_CASE_									=						False
      SCREAMING_SNAKE_CASE_									=						TFFunnelBaseModel(config=_A)
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.last_hidden_state.shape						,		(self.batch_size, 3, self.d_model))

      SCREAMING_SNAKE_CASE_									=						False
      SCREAMING_SNAKE_CASE_									=						TFFunnelBaseModel(config=_A)
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.last_hidden_state.shape						,		(self.batch_size, 2, self.d_model))

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		):
      SCREAMING_SNAKE_CASE_									=						TFFunnelForPreTraining(config=_A)
      SCREAMING_SNAKE_CASE_									=						{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.logits.shape						,		(self.batch_size, self.seq_length))

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		):
      SCREAMING_SNAKE_CASE_									=						TFFunnelForMaskedLM(config=_A)
      SCREAMING_SNAKE_CASE_									=						{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.logits.shape						,		(self.batch_size, self.seq_length, self.vocab_size))

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		):
      SCREAMING_SNAKE_CASE_									=						self.num_labels
      SCREAMING_SNAKE_CASE_									=						TFFunnelForSequenceClassification(config=_A)
      SCREAMING_SNAKE_CASE_									=						{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.logits.shape						,		(self.batch_size, self.num_labels))

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		):
      SCREAMING_SNAKE_CASE_									=						self.num_choices
      SCREAMING_SNAKE_CASE_									=						TFFunnelForMultipleChoice(config=_A)
      SCREAMING_SNAKE_CASE_									=						tf.tile(tf.expand_dims(_A						,		1)						,		(1, self.num_choices, 1))
      SCREAMING_SNAKE_CASE_									=						tf.tile(tf.expand_dims(_A						,		1)						,		(1, self.num_choices, 1))
      SCREAMING_SNAKE_CASE_									=						tf.tile(tf.expand_dims(_A						,		1)						,		(1, self.num_choices, 1))
      SCREAMING_SNAKE_CASE_									=						{
          'input_ids': multiple_choice_inputs_ids,
          'attention_mask': multiple_choice_input_mask,
          'token_type_ids': multiple_choice_token_type_ids,
      }
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.logits.shape						,		(self.batch_size, self.num_choices))

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		):
      SCREAMING_SNAKE_CASE_									=						self.num_labels
      SCREAMING_SNAKE_CASE_									=						TFFunnelForTokenClassification(config=_A)
      SCREAMING_SNAKE_CASE_									=						{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.logits.shape						,		(self.batch_size, self.seq_length, self.num_labels))

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		_A						,		):
      SCREAMING_SNAKE_CASE_									=						TFFunnelForQuestionAnswering(config=_A)
      SCREAMING_SNAKE_CASE_									=						{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.start_logits.shape						,		(self.batch_size, self.seq_length))
      self.parent.assertEqual(result.end_logits.shape						,		(self.batch_size, self.seq_length))


  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.prepare_config_and_inputs()
      (
          (
          SCREAMING_SNAKE_CASE_
      )							,			(
          SCREAMING_SNAKE_CASE_
      )							,			(
          SCREAMING_SNAKE_CASE_
      )							,			(
          SCREAMING_SNAKE_CASE_
      )							,			(
          SCREAMING_SNAKE_CASE_
      )							,			(
          SCREAMING_SNAKE_CASE_
      )							,			(
          SCREAMING_SNAKE_CASE_
      )							,			
      )									=						config_and_inputs
      SCREAMING_SNAKE_CASE_									=						{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
      return config, inputs_dict






@require_tf
class       __snake_case  (    lowerCAmelCase__     , lowerCAmelCase__     , unittest.TestCase       ):
  __lowerCAmelCase     :	Optional[int]						 =  (
      (
          TFFunnelModel,
          TFFunnelForMaskedLM,
          TFFunnelForPreTraining,
          TFFunnelForQuestionAnswering,
          TFFunnelForTokenClassification,
      )
      if is_tf_available()
      else ()
  )
  __lowerCAmelCase     :	Union[str, Any]						 =  (
      {
          'feature-extraction': (TFFunnelBaseModel, TFFunnelModel),
          'fill-mask': TFFunnelForMaskedLM,
          'question-answering': TFFunnelForQuestionAnswering,
          'text-classification': TFFunnelForSequenceClassification,
          'token-classification': TFFunnelForTokenClassification,
          'zero-shot': TFFunnelForSequenceClassification,
      }
      if is_tf_available()
      else {}
  )
  __lowerCAmelCase     :	str						 =  False
  __lowerCAmelCase     :	Union[str, Any]						 =  False

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						TFFunnelModelTester(self)
      SCREAMING_SNAKE_CASE_									=						ConfigTester(self						,		config_class=_A)

  def 						lowerCAmelCase__     (					self):
      self.config_tester.run_common_tests()

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_A)

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_pretraining(*_A)

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_lm(*_A)

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*_A)


  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(*_A)






@require_tf
class       __snake_case  (    lowerCAmelCase__     , unittest.TestCase       ):
  __lowerCAmelCase     :	List[str]						 =  (
      (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
  )
  __lowerCAmelCase     :	Any						 =  False
  __lowerCAmelCase     :	Any						 =  False

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						TFFunnelModelTester(self						,		base=_A)
      SCREAMING_SNAKE_CASE_									=						ConfigTester(self						,		config_class=_A)

  def 						lowerCAmelCase__     (					self):
      self.config_tester.run_common_tests()

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_base_model(*_A)

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(*_A)


  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_multiple_choice(*_A)





from typing import List

import numpy as np


def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		dict       ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						{key: len(_SCREAMING_SNAKE_CASE       ) for key, value in gen_kwargs.items() if isinstance(_SCREAMING_SNAKE_CASE ,   _SCREAMING_SNAKE_CASE       )}
    if len(set(lists_lengths.values()       )       ) > 1:
        raise RuntimeError(
            (
                'Sharding is ambiguous for this dataset: '
                + 'we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n'
                + '\n'.join(f"""\t- key {key} has length {length}""" for key, length in lists_lengths.items()       )
                + '\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, '
                + 'and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.'
            )       )
    SCREAMING_SNAKE_CASE_									=						max(lists_lengths.values() ,   default=0       )
    return max(1 ,   _SCREAMING_SNAKE_CASE       )


def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		int ,   _SCREAMING_SNAKE_CASE					:		int       ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						[]
    for group_idx in range(_SCREAMING_SNAKE_CASE       ):
        SCREAMING_SNAKE_CASE_									=						num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs))
        if num_shards_to_add == 0:
            break
        SCREAMING_SNAKE_CASE_									=						shards_indices_per_group[-1].stop if shards_indices_per_group else 0
        SCREAMING_SNAKE_CASE_									=						range(_SCREAMING_SNAKE_CASE ,   start + num_shards_to_add       )
        shards_indices_per_group.append(_SCREAMING_SNAKE_CASE       )
    return shards_indices_per_group


def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		dict ,   _SCREAMING_SNAKE_CASE					:		int       ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						_number_of_shards_in_gen_kwargs(_SCREAMING_SNAKE_CASE       )
    if num_shards == 1:
        return [dict(_SCREAMING_SNAKE_CASE       )]
    else:
        SCREAMING_SNAKE_CASE_									=						_distribute_shards(num_shards=_SCREAMING_SNAKE_CASE ,   max_num_jobs=_SCREAMING_SNAKE_CASE       )
        return [
            {
                key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]]
                if isinstance(_SCREAMING_SNAKE_CASE ,   _SCREAMING_SNAKE_CASE       )
                else value
                for key, value in gen_kwargs.items()
            }
            for group_idx in range(len(_SCREAMING_SNAKE_CASE       )       )
        ]


def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		List[dict]       ):





    """simple docstring"""


    return {
        key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]]
        if isinstance(gen_kwargs_list[0][key] ,   _SCREAMING_SNAKE_CASE       )
        else gen_kwargs_list[0][key]
        for key in gen_kwargs_list[0]
    }





def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		np.random.Generator ,   _SCREAMING_SNAKE_CASE					:		dict       ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						{len(_SCREAMING_SNAKE_CASE       ) for value in gen_kwargs.values() if isinstance(_SCREAMING_SNAKE_CASE ,   _SCREAMING_SNAKE_CASE       )}
    SCREAMING_SNAKE_CASE_									=						{}
    for size in list_sizes:
        SCREAMING_SNAKE_CASE_									=						list(range(_SCREAMING_SNAKE_CASE       )       )
        rng.shuffle(indices_per_size[size]       )
    # Now let's copy the gen_kwargs and shuffle the lists based on their sizes
    SCREAMING_SNAKE_CASE_									=						dict(_SCREAMING_SNAKE_CASE       )
    for key, value in shuffled_kwargs.items():
        if isinstance(_SCREAMING_SNAKE_CASE ,   _SCREAMING_SNAKE_CASE       ):
            SCREAMING_SNAKE_CASE_									=						[value[i] for i in indices_per_size[len(_SCREAMING_SNAKE_CASE       )]]
    return shuffled_kwargs


