



from typing import Optional, Union

import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig


a_			=					logging.get_logger(__name__)


# General docstring
a_			=					"""MobileNetV1Config"""

# Base docstring
a_			=					"""google/mobilenet_v1_1.0_224"""
a_			=					[1, 1_024, 7, 7]

# Image classification docstring
a_			=					"""google/mobilenet_v1_1.0_224"""
a_			=					"""tabby, tabby cat"""


a_			=					[
    """google/mobilenet_v1_1.0_224""",
    """google/mobilenet_v1_0.75_192""",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]





def 		a__			(		_UpperCamelCase			: Any ,_UpperCamelCase			: Optional[int] ,_UpperCamelCase			: List[Any]=None							):
   __lowerCamelCase													=    {}

   if isinstance(_lowerCamelCase ,_lowerCamelCase							):
      __lowerCamelCase													=    model.mobilenet_va
   else:
      __lowerCamelCase													=    model

   __lowerCamelCase													=    'MobilenetV1/Conv2d_0/'
   __lowerCamelCase													=    backbone.conv_stem.convolution.weight
   __lowerCamelCase													=    backbone.conv_stem.normalization.bias
   __lowerCamelCase													=    backbone.conv_stem.normalization.weight
   __lowerCamelCase													=    backbone.conv_stem.normalization.running_mean
   __lowerCamelCase													=    backbone.conv_stem.normalization.running_var

   for i in range(13							):
      __lowerCamelCase													=    i + 1
      __lowerCamelCase													=    i * 2

      __lowerCamelCase													=    backbone.layer[pt_index]
      __lowerCamelCase													=    F"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
      __lowerCamelCase													=    pointer.convolution.weight
      __lowerCamelCase													=    pointer.normalization.bias
      __lowerCamelCase													=    pointer.normalization.weight
      __lowerCamelCase													=    pointer.normalization.running_mean
      __lowerCamelCase													=    pointer.normalization.running_var

      __lowerCamelCase													=    backbone.layer[pt_index + 1]
      __lowerCamelCase													=    F"""MobilenetV1/Conv2d_{tf_index}_pointwise/"""
      __lowerCamelCase													=    pointer.convolution.weight
      __lowerCamelCase													=    pointer.normalization.bias
      __lowerCamelCase													=    pointer.normalization.weight
      __lowerCamelCase													=    pointer.normalization.running_mean
      __lowerCamelCase													=    pointer.normalization.running_var

   if isinstance(_lowerCamelCase ,_lowerCamelCase							):
      __lowerCamelCase													=    'MobilenetV1/Logits/Conv2d_1c_1x1/'
      __lowerCamelCase													=    model.classifier.weight
      __lowerCamelCase													=    model.classifier.bias

   return tf_to_pt_map





def 		a__			(		_UpperCamelCase			: List[str] ,_UpperCamelCase			: str ,_UpperCamelCase			: Optional[Any]							):



   try:
      import numpy as np
      import tensorflow as tf
   except ImportError:
      logger.error(
          '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '''
          '''https://www.tensorflow.org/install/ for installation instructions.'''							)
      raise

   # Load weights from TF model
   __lowerCamelCase													=    tf.train.list_variables(_lowerCamelCase							)
   __lowerCamelCase													=    {}
   for name, shape in init_vars:
      logger.info(F"""Loading TF weight {name} with shape {shape}"""							)
      __lowerCamelCase													=    tf.train.load_variable(_lowerCamelCase ,_lowerCamelCase							)
      __lowerCamelCase													=    array

   # Build TF to PyTorch weights loading map
   __lowerCamelCase													=    _build_tf_to_pytorch_map(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase							)

   for name, pointer in tf_to_pt_map.items():
      logger.info(F"""Importing {name}"""							)
      if name not in tf_weights:
         logger.info(F"""{name} not in tf pre-trained weights, skipping"""							)
         continue

      __lowerCamelCase													=    tf_weights[name]

      if "depthwise_weights" in name:
         logger.info('''Transposing depthwise'''							)
         __lowerCamelCase													=    np.transpose(_lowerCamelCase ,(2, 3, 0, 1)							)
      elif "weights" in name:
         logger.info('''Transposing'''							)
         if len(pointer.shape							) == 2:  # copying into linear layer
            __lowerCamelCase													=    array.squeeze().transpose()
         else:
            __lowerCamelCase													=    np.transpose(_lowerCamelCase ,(3, 2, 0, 1)							)

      if pointer.shape != array.shape:
         raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched"""							)

      logger.info(F"""Initialize PyTorch weight {name} {array.shape}"""							)
      __lowerCamelCase													=    torch.from_numpy(_lowerCamelCase							)

      tf_weights.pop(_lowerCamelCase ,_lowerCamelCase							)
      tf_weights.pop(name + '''/RMSProp''' ,_lowerCamelCase							)
      tf_weights.pop(name + '''/RMSProp_1''' ,_lowerCamelCase							)
      tf_weights.pop(name + '''/ExponentialMovingAverage''' ,_lowerCamelCase							)

   logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys()							)}"""							)
   return model





def 		a__			(		_UpperCamelCase			: Dict ,_UpperCamelCase			: Union[str, Any]							):
   __lowerCamelCase													=    features.shape[-2:]
   __lowerCamelCase													=    conv_layer.stride
   __lowerCamelCase													=    conv_layer.kernel_size

   if in_height % stride_height == 0:
      __lowerCamelCase													=    max(kernel_height - stride_height ,0							)
   else:
      __lowerCamelCase													=    max(kernel_height - (in_height % stride_height) ,0							)

   if in_width % stride_width == 0:
      __lowerCamelCase													=    max(kernel_width - stride_width ,0							)
   else:
      __lowerCamelCase													=    max(kernel_width - (in_width % stride_width) ,0							)

   __lowerCamelCase													=    pad_along_width // 2
   __lowerCamelCase													=    pad_along_width - pad_left
   __lowerCamelCase													=    pad_along_height // 2
   __lowerCamelCase													=    pad_along_height - pad_top

   __lowerCamelCase													=    (pad_left, pad_right, pad_top, pad_bottom)
   return nn.functional.pad(_lowerCamelCase ,_lowerCamelCase ,'''constant''' ,0.0							)



class  __lowerCAmelCase     (	nn.Module   ):




 def __init__(						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase = 1	,				__UpperCAmelCase = 1	,				__UpperCAmelCase = False	,				__UpperCAmelCase = True	,				__UpperCAmelCase = True	,				):



    '''simple docstring'''
    super().__init__()
    __lowerCamelCase													=    config

    if in_channels % groups != 0:
       raise ValueError(F"""Input channels ({in_channels}) are not divisible by {groups} groups."""				)
    if out_channels % groups != 0:
       raise ValueError(F"""Output channels ({out_channels}) are not divisible by {groups} groups."""				)

    __lowerCamelCase													=    0 if config.tf_padding else int((kernel_size - 1) / 2				)

    __lowerCamelCase													=    nn.Convad(
        in_channels=_A	,				out_channels=_A	,				kernel_size=_A	,				stride=_A	,				padding=_A	,				groups=_A	,				bias=_A	,				padding_mode='''zeros'''	,				)

    if use_normalization:
       __lowerCamelCase													=    nn.BatchNormad(
           num_features=_A	,				eps=config.layer_norm_eps	,				momentum=0.9_997	,				affine=_A	,				track_running_stats=_A	,				)
    else:
       __lowerCamelCase													=    None

    if use_activation:
       if isinstance(_A	,				_A				):
          __lowerCamelCase													=    ACTaFN[use_activation]
       elif isinstance(config.hidden_act	,				_A				):
          __lowerCamelCase													=    ACTaFN[config.hidden_act]
       else:
          __lowerCamelCase													=    config.hidden_act
    else:
       __lowerCamelCase													=    None




 def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



    '''simple docstring'''

    if self.config.tf_padding:
       __lowerCamelCase													=    apply_tf_padding(_A	,				self.convolution				)
    __lowerCamelCase													=    self.convolution(_A				)
    if self.normalization is not None:
       __lowerCamelCase													=    self.normalization(_A				)
    if self.activation is not None:
       __lowerCamelCase													=    self.activation(_A				)
    return features



class  __lowerCAmelCase     (	a__   ):
 lowerCAmelCase__       					=  MobileNetVaConfig
 lowerCAmelCase__       					=  load_tf_weights_in_mobilenet_va
 lowerCAmelCase__       					=  """mobilenet_v1"""
 lowerCAmelCase__       					=  """pixel_values"""
 lowerCAmelCase__       					=  False




 def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



    '''simple docstring'''

    if isinstance(_A	,				(nn.Linear, nn.Convad)				):
       module.weight.data.normal_(mean=0.0	,				std=self.config.initializer_range				)
       if module.bias is not None:
          module.bias.data.zero_()
    elif isinstance(_A	,				nn.BatchNormad				):
       module.bias.data.zero_()
       module.weight.data.fill_(1.0				)



a_			=					R"""
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

a_			=					R"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`MobileNetV1ImageProcessor.__call__`] for details.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""



@add_start_docstrings(
    """The bare MobileNetV1 model outputting raw hidden-states without any specific head on top."""  ,	a__  ,	)
class  __lowerCAmelCase     (	a__   ):




 def __init__(						self	,				__UpperCAmelCase	,				__UpperCAmelCase = True				):



    '''simple docstring'''
    super().__init__(_A				)
    __lowerCamelCase													=    config

    __lowerCamelCase													=    32
    __lowerCamelCase													=    max(int(depth * config.depth_multiplier				)	,				config.min_depth				)

    __lowerCamelCase													=    MobileNetVaConvLayer(
        _A	,				in_channels=config.num_channels	,				out_channels=_A	,				kernel_size=3	,				stride=2	,				)

    __lowerCamelCase													=    [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

    __lowerCamelCase													=    nn.ModuleList()
    for i in range(13				):
       __lowerCamelCase													=    out_channels

       if strides[i] == 2 or i == 0:
          depth *= 2
          __lowerCamelCase													=    max(int(depth * config.depth_multiplier				)	,				config.min_depth				)

       self.layer.append(
           MobileNetVaConvLayer(
               _A	,				in_channels=_A	,				out_channels=_A	,				kernel_size=3	,				stride=strides[i]	,				groups=_A	,				)				)

       self.layer.append(
           MobileNetVaConvLayer(
               _A	,				in_channels=_A	,				out_channels=_A	,				kernel_size=1	,				)				)

    __lowerCamelCase													=    nn.AdaptiveAvgPoolad((1, 1)				) if add_pooling_layer else None

    # Initialize weights and apply final processing
    self.post_init()




 def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



    '''simple docstring'''
    raise NotImplementedError




 @add_start_docstrings_to_model_forward(_A				)
 @add_code_sample_docstrings(
     checkpoint=_CHECKPOINT_FOR_DOC	,				output_type=_A	,				config_class=_CONFIG_FOR_DOC	,				modality='''vision'''	,				expected_output=_EXPECTED_OUTPUT_SHAPE	,				)
 def        lowerCamelCase      (						self	,				__UpperCAmelCase = None	,				__UpperCAmelCase = None	,				__UpperCAmelCase = None	,				):



    '''simple docstring'''
    __lowerCamelCase													=    (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    __lowerCamelCase													=    return_dict if return_dict is not None else self.config.use_return_dict

    if pixel_values is None:
       raise ValueError('''You have to specify pixel_values'''				)

    __lowerCamelCase													=    self.conv_stem(_A				)

    __lowerCamelCase													=    () if output_hidden_states else None

    for i, layer_module in enumerate(self.layer				):
       __lowerCamelCase													=    layer_module(_A				)

       if output_hidden_states:
          __lowerCamelCase													=    all_hidden_states + (hidden_states,)

    __lowerCamelCase													=    hidden_states

    if self.pooler is not None:
       __lowerCamelCase													=    torch.flatten(self.pooler(_A				)	,				start_dim=1				)
    else:
       __lowerCamelCase													=    None

    if not return_dict:
       return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None				)

    return BaseModelOutputWithPoolingAndNoAttention(
        last_hidden_state=_A	,				pooler_output=_A	,				hidden_states=_A	,				)



@add_start_docstrings(
    """\n    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    """  ,	a__  ,	)
class  __lowerCAmelCase     (	a__   ):




 def __init__(						self	,				__UpperCAmelCase				):



    '''simple docstring'''
    super().__init__(_A				)

    __lowerCamelCase													=    config.num_labels
    __lowerCamelCase													=    MobileNetVaModel(_A				)

    __lowerCamelCase													=    self.mobilenet_va.layer[-1].convolution.out_channels

    # Classifier head
    __lowerCamelCase													=    nn.Dropout(config.classifier_dropout_prob	,				inplace=_A				)
    __lowerCamelCase													=    nn.Linear(_A	,				config.num_labels				) if config.num_labels > 0 else nn.Identity()

    # Initialize weights and apply final processing
    self.post_init()




 @add_start_docstrings_to_model_forward(_A				)
 @add_code_sample_docstrings(
     checkpoint=_IMAGE_CLASS_CHECKPOINT	,				output_type=_A	,				config_class=_CONFIG_FOR_DOC	,				expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT	,				)
 def        lowerCamelCase      (						self	,				__UpperCAmelCase = None	,				__UpperCAmelCase = None	,				__UpperCAmelCase = None	,				__UpperCAmelCase = None	,				):



    '''simple docstring'''
    __lowerCamelCase													=    return_dict if return_dict is not None else self.config.use_return_dict

    __lowerCamelCase													=    self.mobilenet_va(_A	,				output_hidden_states=_A	,				return_dict=_A				)

    __lowerCamelCase													=    outputs.pooler_output if return_dict else outputs[1]

    __lowerCamelCase													=    self.classifier(self.dropout(_A				)				)

    __lowerCamelCase													=    None
    if labels is not None:
       if self.config.problem_type is None:
          if self.num_labels == 1:
             __lowerCamelCase													=    'regression'
          elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
             __lowerCamelCase													=    'single_label_classification'
          else:
             __lowerCamelCase													=    'multi_label_classification'

       if self.config.problem_type == "regression":
          __lowerCamelCase													=    MSELoss()
          if self.num_labels == 1:
             __lowerCamelCase													=    loss_fct(logits.squeeze()	,				labels.squeeze()				)
          else:
             __lowerCamelCase													=    loss_fct(_A	,				_A				)
       elif self.config.problem_type == "single_label_classification":
          __lowerCamelCase													=    CrossEntropyLoss()
          __lowerCamelCase													=    loss_fct(logits.view(-1	,				self.num_labels				)	,				labels.view(-1				)				)
       elif self.config.problem_type == "multi_label_classification":
          __lowerCamelCase													=    BCEWithLogitsLoss()
          __lowerCamelCase													=    loss_fct(_A	,				_A				)

    if not return_dict:
       __lowerCamelCase													=    (logits,) + outputs[2:]
       return ((loss,) + output) if loss is not None else output

    return ImageClassifierOutputWithNoAttention(
        loss=_A	,				logits=_A	,				hidden_states=outputs.hidden_states	,				)











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  __lowerCAmelCase     :




 def __init__(						self	,				__UpperCAmelCase	,				__UpperCAmelCase=13	,				__UpperCAmelCase=7	,				__UpperCAmelCase=True	,				__UpperCAmelCase=True	,				__UpperCAmelCase=True	,				__UpperCAmelCase=True	,				__UpperCAmelCase=99	,				__UpperCAmelCase=[1, 1, 2]	,				__UpperCAmelCase=1	,				__UpperCAmelCase=32	,				__UpperCAmelCase=4	,				__UpperCAmelCase=8	,				__UpperCAmelCase=37	,				__UpperCAmelCase="gelu_new"	,				__UpperCAmelCase=0.1	,				__UpperCAmelCase=0.1	,				__UpperCAmelCase=0.0	,				__UpperCAmelCase=512	,				__UpperCAmelCase=3	,				__UpperCAmelCase=0.02	,				__UpperCAmelCase=3	,				__UpperCAmelCase=4	,				__UpperCAmelCase=None	,				__UpperCAmelCase=False	,				):



    '''simple docstring'''
    __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													=    block_sizes
    __lowerCamelCase													=    num_decoder_layers
    __lowerCamelCase													=    d_model
    __lowerCamelCase													=    n_head
    __lowerCamelCase													=    d_head
    __lowerCamelCase													=    d_inner
    __lowerCamelCase													=    hidden_act
    __lowerCamelCase													=    hidden_dropout
    __lowerCamelCase													=    attention_dropout
    __lowerCamelCase													=    activation_dropout
    __lowerCamelCase													=    max_position_embeddings
    __lowerCamelCase													=    type_vocab_size
    __lowerCamelCase													=    2
    __lowerCamelCase													=    num_labels
    __lowerCamelCase													=    num_choices
    __lowerCamelCase													=    scope
    __lowerCamelCase													=    initializer_std

    # Used in the tests to check the size of the first attention layer
    __lowerCamelCase													=    n_head
    # Used in the tests to check the size of the first hidden state
    __lowerCamelCase													=    self.d_model
    # Used in the tests to check the number of output hidden states/attentions
    __lowerCamelCase													=    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:
       __lowerCamelCase													=    self.num_hidden_layers + 2




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __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													=    None
    if self.use_token_type_ids:
       __lowerCamelCase													=    ids_tensor([self.batch_size, self.seq_length]	,				self.type_vocab_size				)

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

    __lowerCamelCase													=    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	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelModel(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)

    __lowerCamelCase													=    [input_ids, input_mask]
    __lowerCamelCase													=    model(__UpperCAmelCase				)

    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.last_hidden_state.shape	,				(self.batch_size, self.seq_length, self.d_model)				)

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

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




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelBaseModel(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)

    __lowerCamelCase													=    [input_ids, input_mask]
    __lowerCamelCase													=    model(__UpperCAmelCase				)

    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.last_hidden_state.shape	,				(self.batch_size, 2, self.d_model)				)

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

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




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelForPreTraining(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.seq_length)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelForMaskedLM(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.seq_length, self.vocab_size)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    self.num_labels
    __lowerCamelCase													=    TFFunnelForSequenceClassification(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.num_labels)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    self.num_choices
    __lowerCamelCase													=    TFFunnelForMultipleChoice(config=__UpperCAmelCase				)
    __lowerCamelCase													=    tf.tile(tf.expand_dims(__UpperCAmelCase	,				1				)	,				(1, self.num_choices, 1)				)
    __lowerCamelCase													=    tf.tile(tf.expand_dims(__UpperCAmelCase	,				1				)	,				(1, self.num_choices, 1)				)
    __lowerCamelCase													=    tf.tile(tf.expand_dims(__UpperCAmelCase	,				1				)	,				(1, self.num_choices, 1)				)
    __lowerCamelCase													=    {
        '''input_ids''': multiple_choice_inputs_ids,
        '''attention_mask''': multiple_choice_input_mask,
        '''token_type_ids''': multiple_choice_token_type_ids,
    }
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.num_choices)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    self.num_labels
    __lowerCamelCase													=    TFFunnelForTokenClassification(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.seq_length, self.num_labels)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelForQuestionAnswering(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    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				):



    '''simple docstring'''
    __lowerCamelCase													=    self.prepare_config_and_inputs()
    (
        (
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,
    )													=    config_and_inputs
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
    return config, inputs_dict



@require_tf
class  __lowerCAmelCase     (	lowerCAmelCase__  ,	lowerCAmelCase__  ,	unittest.TestCase   ):
 lowerCAmelCase__       					=  (
     (
         TFFunnelModel,
         TFFunnelForMaskedLM,
         TFFunnelForPreTraining,
         TFFunnelForQuestionAnswering,
         TFFunnelForTokenClassification,
     )
     if is_tf_available()
     else ()
 )
 lowerCAmelCase__       					=  (
     {
         """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__       					=  False
 lowerCAmelCase__       					=  False




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelModelTester(self				)
    __lowerCamelCase													=    ConfigTester(self	,				config_class=__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    self.config_tester.run_common_tests()




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_pretraining(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase				)



@require_tf
class  __lowerCAmelCase     (	lowerCAmelCase__  ,	unittest.TestCase   ):
 lowerCAmelCase__       					=  (
     (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
 )
 lowerCAmelCase__       					=  False
 lowerCAmelCase__       					=  False




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelModelTester(self	,				base=__UpperCAmelCase				)
    __lowerCamelCase													=    ConfigTester(self	,				config_class=__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    self.config_tester.run_common_tests()




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_base_model(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_multiple_choice(*__UpperCAmelCase				)






