


"""simple docstring"""






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

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, logging, randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin


lowercase  		=			logging.get_logger(__name__)  # pylint: disable=invalid-name


@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerAncestralDiscrete
class 			SCREAMING_SNAKE_CASE_  (   _lowercase):




							'''simple docstring'''





							__magic_name__					:     torch.FloatTensor
							__magic_name__					:     Optional[torch.FloatTensor]				  =  None



def 			A__		(					_UpperCAmelCase    :      int				,    _UpperCAmelCase    :      Optional[int]=0.9_9_9				,    _UpperCAmelCase    :      str="cosine"				,    )							->	List[str]:

	'''simple docstring'''


	if alpha_transform_type == "cosine":

		def alpha_bar_fn(_UpperCAmelCase    :      Tuple	):
			return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2	) ** 2

	elif alpha_transform_type == "exp":

		def alpha_bar_fn(_UpperCAmelCase    :      Union[str, Any]	):
			return math.exp(t * -1_2.0	)

	else:
		raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}"""	)

	snake_case__  :						List[str]		=      []
	for i in range(_UpperCAmelCase	):
		snake_case__  :						str		=      i / num_diffusion_timesteps
		snake_case__  :						List[Any]		=      (i + 1) / num_diffusion_timesteps
		betas.append(min(1 - alpha_bar_fn(_UpperCAmelCase	) / alpha_bar_fn(_UpperCAmelCase	)				,    _UpperCAmelCase	)	)
	return torch.tensor(_UpperCAmelCase				,    dtype=torch.floataa	)



class 			SCREAMING_SNAKE_CASE_  (   _lowercase	,      _lowercase):




							'''simple docstring'''





							__magic_name__					:     Optional[int]				  =  [e.name for e in KarrasDiffusionSchedulers]
							__magic_name__					:     Dict				  =  1




							@register_to_config
							def __init__(						self	,					lowerCamelCase__ = 1_000	,					lowerCamelCase__ = 0.00_01	,					lowerCamelCase__ = 0.02	,					lowerCamelCase__ = "linear"	,					lowerCamelCase__ = None	,					lowerCamelCase__ = "epsilon"	,					lowerCamelCase__ = "linspace"	,					lowerCamelCase__ = 0	,					)   ->	Optional[Any]:







								'''simple docstring'''




								if trained_betas is not None:
									snake_case__  :						List[Any]		=      torch.tensor(lowerCamelCase__	,					dtype=torch.floataa)
								elif beta_schedule == "linear":
									snake_case__  :						Tuple		=      torch.linspace(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					dtype=torch.floataa)
								elif beta_schedule == "scaled_linear":
									# this schedule is very specific to the latent diffusion model.
									snake_case__  :						Optional[int]		=      (
									    torch.linspace(beta_start**0.5	,					beta_end**0.5	,					lowerCamelCase__	,					dtype=torch.floataa) ** 2
									)
								elif beta_schedule == "squaredcos_cap_v2":
									# Glide cosine schedule
									snake_case__  :						List[str]		=      betas_for_alpha_bar(lowerCamelCase__)
								else:
									raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""")

								snake_case__  :						Dict		=      1.0 - self.betas
								snake_case__  :						Tuple		=      torch.cumprod(self.alphas	,					dim=0)

								snake_case__  :						Dict		=      np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
								snake_case__  :						str		=      np.concatenate([sigmas[::-1], [0.0]]).astype(np.floataa)
								snake_case__  :						Any		=      torch.from_numpy(lowerCamelCase__)

								# setable values
								snake_case__  :						Union[str, Any]		=      None
								snake_case__  :						Union[str, Any]		=      np.linspace(0	,					num_train_timesteps - 1	,					lowerCamelCase__	,					dtype=lowerCamelCase__)[::-1].copy()
								snake_case__  :						Optional[int]		=      torch.from_numpy(lowerCamelCase__)
								snake_case__  :						Tuple		=      False




							@property
							def        UpperCAmelCase (						self)   ->	Any:







								'''simple docstring'''




								if self.config.timestep_spacing in ["linspace", "trailing"]:
									return self.sigmas.max()

								return (self.sigmas.max() ** 2 + 1) ** 0.5




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__)   ->	torch.FloatTensor:







								'''simple docstring'''




								if isinstance(lowerCamelCase__	,					torch.Tensor):
									snake_case__  :						Dict		=      timestep.to(self.timesteps.device)
								snake_case__  :						Dict		=      (self.timesteps == timestep).nonzero().item()
								snake_case__  :						int		=      self.sigmas[step_index]
								snake_case__  :						str		=      sample / ((sigma**2 + 1) ** 0.5)
								snake_case__  :						Tuple		=      True
								return sample




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__ = None)   ->	int:







								'''simple docstring'''




								snake_case__  :						Union[str, Any]		=      num_inference_steps

								# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
								if self.config.timestep_spacing == "linspace":
									snake_case__  :						Optional[int]		=      np.linspace(0	,					self.config.num_train_timesteps - 1	,					lowerCamelCase__	,					dtype=lowerCamelCase__)[
									    ::-1
									].copy()
								elif self.config.timestep_spacing == "leading":
									snake_case__  :						Optional[int]		=      self.config.num_train_timesteps // self.num_inference_steps
									# creates integer timesteps by multiplying by ratio
									# casting to int to avoid issues when num_inference_step is power of 3
									snake_case__  :						Optional[Any]		=      (np.arange(0	,					lowerCamelCase__) * step_ratio).round()[::-1].copy().astype(lowerCamelCase__)
									timesteps += self.config.steps_offset
								elif self.config.timestep_spacing == "trailing":
									snake_case__  :						Optional[int]		=      self.config.num_train_timesteps / self.num_inference_steps
									# creates integer timesteps by multiplying by ratio
									# casting to int to avoid issues when num_inference_step is power of 3
									snake_case__  :						Tuple		=      (np.arange(self.config.num_train_timesteps	,					0	,					-step_ratio)).round().copy().astype(lowerCamelCase__)
									timesteps -= 1
								else:
									raise ValueError(
									    f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""")

								snake_case__  :						List[Any]		=      np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
								snake_case__  :						List[str]		=      np.interp(lowerCamelCase__	,					np.arange(0	,					len(lowerCamelCase__))	,					lowerCamelCase__)
								snake_case__  :						List[Any]		=      np.concatenate([sigmas, [0.0]]).astype(np.floataa)
								snake_case__  :						Optional[Any]		=      torch.from_numpy(lowerCamelCase__).to(device=lowerCamelCase__)
								if str(lowerCamelCase__).startswith("mps"):
									# mps does not support float64
									snake_case__  :						int		=      torch.from_numpy(lowerCamelCase__).to(lowerCamelCase__	,					dtype=torch.floataa)
								else:
									snake_case__  :						Optional[int]		=      torch.from_numpy(lowerCamelCase__).to(device=lowerCamelCase__)




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__ = None	,					lowerCamelCase__ = True	,					)   ->	Union[EulerAncestralDiscreteSchedulerOutput, Tuple]:







								'''simple docstring'''




								if (
								    isinstance(lowerCamelCase__	,					lowerCamelCase__)
								    or isinstance(lowerCamelCase__	,					torch.IntTensor)
								    or isinstance(lowerCamelCase__	,					torch.LongTensor)
								):
									raise ValueError(
									    (
									        "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
									        " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
									        " one of the `scheduler.timesteps` as a timestep."
									    )	,					)

								if not self.is_scale_input_called:
									logger.warning(
									    "The `scale_model_input` function should be called before `step` to ensure correct denoising. "
									    "See `StableDiffusionPipeline` for a usage example.")

								if isinstance(lowerCamelCase__	,					torch.Tensor):
									snake_case__  :						Tuple		=      timestep.to(self.timesteps.device)

								snake_case__  :						List[str]		=      (self.timesteps == timestep).nonzero().item()
								snake_case__  :						Dict		=      self.sigmas[step_index]

								# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
								if self.config.prediction_type == "epsilon":
									snake_case__  :						Optional[Any]		=      sample - sigma * model_output
								elif self.config.prediction_type == "v_prediction":
									# * c_out + input * c_skip
									snake_case__  :						Optional[int]		=      model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
								elif self.config.prediction_type == "sample":
									raise NotImplementedError("prediction_type not implemented yet: sample")
								else:
									raise ValueError(
									    f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""")

								snake_case__  :						List[Any]		=      self.sigmas[step_index]
								snake_case__  :						List[str]		=      self.sigmas[step_index + 1]
								snake_case__  :						Any		=      (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5
								snake_case__  :						Union[str, Any]		=      (sigma_to**2 - sigma_up**2) ** 0.5

								# 2. Convert to an ODE derivative
								snake_case__  :						Union[str, Any]		=      (sample - pred_original_sample) / sigma

								snake_case__  :						Union[str, Any]		=      sigma_down - sigma

								snake_case__  :						List[Any]		=      sample + derivative * dt

								snake_case__  :						List[str]		=      model_output.device
								snake_case__  :						Optional[Any]		=      randn_tensor(model_output.shape	,					dtype=model_output.dtype	,					device=lowerCamelCase__	,					generator=lowerCamelCase__)

								snake_case__  :						List[Any]		=      prev_sample + noise * sigma_up

								if not return_dict:
									return (prev_sample,)

								return EulerAncestralDiscreteSchedulerOutput(
								    prev_sample=lowerCamelCase__	,					pred_original_sample=lowerCamelCase__)




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					)   ->	torch.FloatTensor:







								'''simple docstring'''




								snake_case__  :						Tuple		=      self.sigmas.to(device=original_samples.device	,					dtype=original_samples.dtype)
								if original_samples.device.type == "mps" and torch.is_floating_point(lowerCamelCase__):
									# mps does not support float64
									snake_case__  :						Dict		=      self.timesteps.to(original_samples.device	,					dtype=torch.floataa)
									snake_case__  :						Dict		=      timesteps.to(original_samples.device	,					dtype=torch.floataa)
								else:
									snake_case__  :						int		=      self.timesteps.to(original_samples.device)
									snake_case__  :						Optional[int]		=      timesteps.to(original_samples.device)

								snake_case__  :						List[Any]		=      [(schedule_timesteps == t).nonzero().item() for t in timesteps]

								snake_case__  :						str		=      sigmas[step_indices].flatten()
								while len(sigma.shape) < len(original_samples.shape):
									snake_case__  :						List[str]		=      sigma.unsqueeze(-1)

								snake_case__  :						List[Any]		=      original_samples + noise * sigma
								return noisy_samples







							def __len__(						self)   ->	Optional[int]:







								'''simple docstring'''




								return self.config.num_train_timesteps






"""simple docstring"""


import unittest

from transformers import FunnelConfig, FunnelTokenizer, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

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 (
        MODEL_FOR_PRETRAINING_MAPPING,
        FunnelBaseModel,
        FunnelForMaskedLM,
        FunnelForMultipleChoice,
        FunnelForPreTraining,
        FunnelForQuestionAnswering,
        FunnelForSequenceClassification,
        FunnelForTokenClassification,
        FunnelModel,
    )




class 					UpperCamelCase   :







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

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







       def 						a_		(					self) -> Optional[int]:
            snake_case_   			=   ids_tensor([self.batch_size, self.seq_length],				self.vocab_size)

            snake_case_   			=   None
            if self.use_input_mask:
                 snake_case_   			=   ids_tensor([self.batch_size, self.seq_length],				vocab_size=2)

            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_   			=   ids_tensor([self.batch_size, self.seq_length],				1)

            snake_case_   			=   self.get_config()

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







       def 						a_		(					self) -> Dict:
            return 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,				)







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				) -> Tuple:
            snake_case_   			=   FunnelModel(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_   			=   model(lowerCAmelCase__,				attention_mask=lowerCAmelCase__,				token_type_ids=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.d_model))

            snake_case_   			=   False
            snake_case_   			=   model(lowerCAmelCase__)
            self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, self.seq_length, self.d_model))

            snake_case_   			=   False
            snake_case_   			=   model(lowerCAmelCase__)
            self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, self.seq_length, self.d_model))







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				) -> Any:
            snake_case_   			=   FunnelBaseModel(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_   			=   model(lowerCAmelCase__,				attention_mask=lowerCAmelCase__,				token_type_ids=lowerCAmelCase__)
            snake_case_   			=   model(lowerCAmelCase__,				token_type_ids=lowerCAmelCase__)
            snake_case_   			=   model(lowerCAmelCase__)
            self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, 2, self.d_model))

            snake_case_   			=   False
            snake_case_   			=   model(lowerCAmelCase__)
            self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, 3, self.d_model))

            snake_case_   			=   False
            snake_case_   			=   model(lowerCAmelCase__)
            self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, 2, self.d_model))







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				) -> List[Any]:
            snake_case_   			=   self.num_labels
            snake_case_   			=   FunnelForPreTraining(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_   			=   model(lowerCAmelCase__,				attention_mask=lowerCAmelCase__,				token_type_ids=lowerCAmelCase__,				labels=lowerCAmelCase__)
            self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.seq_length))







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				) -> str:
            snake_case_   			=   FunnelForMaskedLM(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_   			=   model(lowerCAmelCase__,				attention_mask=lowerCAmelCase__,				token_type_ids=lowerCAmelCase__,				labels=lowerCAmelCase__)
            self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.seq_length, self.vocab_size))







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				) -> Optional[int]:
            snake_case_   			=   self.num_labels
            snake_case_   			=   FunnelForSequenceClassification(lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_   			=   model(lowerCAmelCase__,				attention_mask=lowerCAmelCase__,				token_type_ids=lowerCAmelCase__,				labels=lowerCAmelCase__)
            self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.num_labels))







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				) -> Optional[int]:
            snake_case_   			=   self.num_choices
            snake_case_   			=   FunnelForMultipleChoice(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_   			=   input_ids.unsqueeze(1).expand(-1,				self.num_choices,				-1).contiguous()
            snake_case_   			=   token_type_ids.unsqueeze(1).expand(-1,				self.num_choices,				-1).contiguous()
            snake_case_   			=   input_mask.unsqueeze(1).expand(-1,				self.num_choices,				-1).contiguous()
            snake_case_   			=   model(
                lowerCAmelCase__,				attention_mask=lowerCAmelCase__,				token_type_ids=lowerCAmelCase__,				labels=lowerCAmelCase__,				)
            self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.num_choices))







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				) -> Tuple:
            snake_case_   			=   self.num_labels
            snake_case_   			=   FunnelForTokenClassification(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_   			=   model(lowerCAmelCase__,				attention_mask=lowerCAmelCase__,				token_type_ids=lowerCAmelCase__,				labels=lowerCAmelCase__)
            self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.seq_length, self.num_labels))







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				) -> int:
            snake_case_   			=   FunnelForQuestionAnswering(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_   			=   model(
                lowerCAmelCase__,				attention_mask=lowerCAmelCase__,				token_type_ids=lowerCAmelCase__,				start_positions=lowerCAmelCase__,				end_positions=lowerCAmelCase__,				)
            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 						a_		(					self) -> Optional[int]:
            snake_case_   			=   self.prepare_config_and_inputs()
            (
                (
                snake_case_
            )			,      (
                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, 'attention_mask': input_mask}
            return config, inputs_dict




@require_torch
class 					UpperCamelCase   (							lowerCAmelCase__       ,						lowerCAmelCase__       ,						unittest.TestCase  ):
       SCREAMING_SNAKE_CASE_						      = False
       SCREAMING_SNAKE_CASE_						      = False
       SCREAMING_SNAKE_CASE_						      = (
           (
               FunnelModel,
               FunnelForMaskedLM,
               FunnelForPreTraining,
               FunnelForQuestionAnswering,
               FunnelForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       SCREAMING_SNAKE_CASE_						      = (
           {
               "feature-extraction": (FunnelBaseModel, FunnelModel),
               "fill-mask": FunnelForMaskedLM,
               "question-answering": FunnelForQuestionAnswering,
               "text-classification": FunnelForSequenceClassification,
               "token-classification": FunnelForTokenClassification,
               "zero-shot": FunnelForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__=False) -> List[Any]:
            snake_case_   			=   super()._prepare_for_class(lowerCAmelCase__,				lowerCAmelCase__,				return_labels=lowerCAmelCase__)

            if return_labels:
                 if model_class in get_values(lowerCAmelCase__):
                      snake_case_   			=   torch.zeros(
                          (self.model_tester.batch_size, self.model_tester.seq_length),				dtype=torch.long,				device=lowerCAmelCase__)
            return inputs_dict







       def 						a_		(					self) -> List[Any]:
            snake_case_   			=   FunnelModelTester(self)
            snake_case_   			=   ConfigTester(self,				config_class=lowerCAmelCase__)







       def 						a_		(					self) -> Tuple:
            self.config_tester.run_common_tests()







       def 						a_		(					self) -> Dict:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*lowerCAmelCase__)







       def 						a_		(					self) -> Optional[Any]:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase__)







       def 						a_		(					self) -> List[str]:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__)







       def 						a_		(					self) -> int:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase__)







       def 						a_		(					self) -> Any:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__)







       def 						a_		(					self,				lowerCAmelCase__) -> int:
            if hasattr(lowerCAmelCase__,				'weight') and module.weight is not None:
                 module.weight.data.fill_(3)
            if hasattr(lowerCAmelCase__,				'bias') and module.bias is not None:
                 module.bias.data.fill_(3)

            for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
                 if hasattr(lowerCAmelCase__,				lowerCAmelCase__) and getattr(lowerCAmelCase__,				lowerCAmelCase__) is not None:
                      snake_case_   			=   getattr(lowerCAmelCase__,				lowerCAmelCase__)
                      weight.data.fill_(3)




@require_torch
class 					UpperCamelCase   (							lowerCAmelCase__       ,						unittest.TestCase  ):
       SCREAMING_SNAKE_CASE_						      = False
       SCREAMING_SNAKE_CASE_						      = False
       SCREAMING_SNAKE_CASE_						      = (
           (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
       )







       def 						a_		(					self) -> List[Any]:
            snake_case_   			=   FunnelModelTester(self,				base=lowerCAmelCase__)
            snake_case_   			=   ConfigTester(self,				config_class=lowerCAmelCase__)







       def 						a_		(					self) -> Tuple:
            self.config_tester.run_common_tests()







       def 						a_		(					self) -> str:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_base_model(*lowerCAmelCase__)







       def 						a_		(					self) -> Optional[Any]:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__)







       def 						a_		(					self) -> List[Any]:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase__)







       def 						a_		(					self) -> Union[str, Any]:
            snake_case_			,      snake_case_   			=   self.model_tester.prepare_config_and_inputs_for_common()
            snake_case_   			=   True

            for model_class in self.all_model_classes:
                 if model_class.__name__ == "FunnelBaseModel":
                      continue
                 snake_case_   			=   model_class(lowerCAmelCase__)
                 model.to(lowerCAmelCase__)
                 model.train()
                 snake_case_   			=   self._prepare_for_class(lowerCAmelCase__,				lowerCAmelCase__,				return_labels=lowerCAmelCase__)
                 snake_case_   			=   model(**lowerCAmelCase__).loss
                 loss.backward()







       def 						a_		(					self,				lowerCAmelCase__) -> Any:
            if hasattr(lowerCAmelCase__,				'weight') and module.weight is not None:
                 module.weight.data.fill_(3)
            if hasattr(lowerCAmelCase__,				'bias') and module.bias is not None:
                 module.bias.data.fill_(3)

            for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
                 if hasattr(lowerCAmelCase__,				lowerCAmelCase__) and getattr(lowerCAmelCase__,				lowerCAmelCase__) is not None:
                      snake_case_   			=   getattr(lowerCAmelCase__,				lowerCAmelCase__)
                      weight.data.fill_(3)




@require_torch
@require_sentencepiece
@require_tokenizers
class 					UpperCamelCase   (							unittest.TestCase  ):







       def 						a_		(					self) -> Any:
            snake_case_   			=   13
            snake_case_   			=   7
            snake_case_   			=   torch.arange(0,				batch_size * sequence_length).long().reshape(lowerCAmelCase__,				lowerCAmelCase__)
            snake_case_   			=   [0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
            snake_case_   			=   torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths])

            snake_case_   			=   FunnelModel.from_pretrained('sgugger/funnel-random-tiny')
            snake_case_   			=   model(lowerCAmelCase__,				token_type_ids=lowerCAmelCase__)[0].abs()

            snake_case_   			=   torch.tensor(2344.8352)
            snake_case_   			=   torch.tensor(0.8052)
            self.assertTrue(torch.allclose(output.sum(),				lowerCAmelCase__,				atol=1e-4))
            self.assertTrue(torch.allclose(output.mean(),				lowerCAmelCase__,				atol=1e-4))

            snake_case_   			=   torch.tensor([[1] * 7, [1] * 4 + [0] * 3] * 6 + [[0, 1, 1, 0, 0, 1, 1]])
            snake_case_   			=   model(lowerCAmelCase__,				attention_mask=lowerCAmelCase__,				token_type_ids=lowerCAmelCase__)[0].abs()

            snake_case_   			=   torch.tensor(2343.8425)
            snake_case_   			=   torch.tensor(0.8049)
            self.assertTrue(torch.allclose(output.sum(),				lowerCAmelCase__,				atol=1e-4))
            self.assertTrue(torch.allclose(output.mean(),				lowerCAmelCase__,				atol=1e-4))







       @slow
       def 						a_		(					self) -> str:
            snake_case_   			=   FunnelTokenizer.from_pretrained('huggingface/funnel-small')
            snake_case_   			=   FunnelModel.from_pretrained('huggingface/funnel-small')
            snake_case_   			=   tokenizer('Hello! I am the Funnel Transformer model.',				return_tensors='pt')
            snake_case_   			=   model(**lowerCAmelCase__)[0]

            snake_case_   			=   torch.tensor(235.7246)
            snake_case_   			=   torch.tensor(0.0256)
            self.assertTrue(torch.allclose(output.sum(),				lowerCAmelCase__,				atol=1e-4))
            self.assertTrue(torch.allclose(output.mean(),				lowerCAmelCase__,				atol=1e-4))

