



from typing import List, Optional, Union

import torch

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


SCREAMING_SNAKE_CASE_:Optional[int] 			=		logging.get_logger(__name__)  # pylint: disable=invalid-name

SCREAMING_SNAKE_CASE_:Tuple 			=		"""
    Examples:
        ```py
        >>> import torch
        >>> import numpy as np

        >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline
        >>> from transformers import pipeline
        >>> from diffusers.utils import load_image


        >>> def make_hint(image, depth_estimator):
        ...     image = depth_estimator(image)[\"depth\"]
        ...     image = np.array(image)
        ...     image = image[:, :, None]
        ...     image = np.concatenate([image, image, image], axis=2)
        ...     detected_map = torch.from_numpy(image).float() / 255.0
        ...     hint = detected_map.permute(2, 0, 1)
        ...     return hint


        >>> depth_estimator = pipeline(\"depth-estimation\")

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16
        ... )
        >>> pipe_prior = pipe_prior.to(\"cuda\")

        >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16
        ... )
        >>> pipe = pipe.to(\"cuda\")


        >>> img = load_image(
        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"
        ...     \"/kandinsky/cat.png\"
        ... ).resize((768, 768))

        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")

        >>> prompt = \"A robot, 4k photo\"
        >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"

        >>> generator = torch.Generator(device=\"cuda\").manual_seed(43)

        >>> image_emb, zero_image_emb = pipe_prior(
        ...     prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator
        ... ).to_tuple()

        >>> images = pipe(
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     hint=hint,
        ...     num_inference_steps=50,
        ...     generator=generator,
        ...     height=768,
        ...     width=768,
        ... ).images

        >>> images[0].save(\"robot_cat.png\")
        ```
"""




def       __UpperCamelCase      (    _lowerCAmelCase ,	_lowerCAmelCase ,	_lowerCAmelCase=8						)			->    Any:



    """simple docstring"""






    A					:			int		=  height // scale_factor**2
    if height % scale_factor**2 != 0:
        new_height += 1
    A					:			List[Any]		=  width // scale_factor**2
    if width % scale_factor**2 != 0:
        new_width += 1
    return new_height * scale_factor, new_width * scale_factor






class SCREAMING_SNAKE_CASE__	(						SCREAMING_SNAKE_CASE_       ):




    '''simple docstring'''






    def __init__(			self,						lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__,						):
        super().__init__()

        self.register_modules(
            unet=lowerCamelCase__,						scheduler=lowerCamelCase__,						movq=lowerCamelCase__,						)
        A					:			List[str]		=  2 ** (len(self.movq.config.block_out_channels						) - 1)






    def      _lowerCAmelCase   (			self,						lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__						):


        if latents is None:
            A					:			str		=  randn_tensor(lowerCamelCase__,						generator=lowerCamelCase__,						device=lowerCamelCase__,						dtype=lowerCamelCase__						)
        else:
            if latents.shape != shape:
                raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''						)
            A					:			Optional[int]		=  latents.to(lowerCamelCase__						)

        A					:			Any		=  latents * scheduler.init_noise_sigma
        return latents






    def      _lowerCAmelCase   (			self,						lowerCamelCase__=0						):


        if is_accelerate_available():
            from accelerate import cpu_offload
        else:
            raise ImportError("""Please install accelerate via `pip install accelerate`"""						)

        A					:			Any		=  torch.device(f'''cuda:{gpu_id}'''						)

        A					:			Union[str, Any]		=  [
            self.unet,
            self.movq,
        ]
        for cpu_offloaded_model in models:
            if cpu_offloaded_model is not None:
                cpu_offload(lowerCamelCase__,						lowerCamelCase__						)






    def      _lowerCAmelCase   (			self,						lowerCamelCase__=0						):


        if is_accelerate_available() and is_accelerate_version(""">=""",						"""0.17.0.dev0"""						):
            from accelerate import cpu_offload_with_hook
        else:
            raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."""						)

        A					:			Optional[int]		=  torch.device(f'''cuda:{gpu_id}'''						)

        if self.device.type != "cpu":
            self.to("""cpu""",						silence_dtype_warnings=lowerCamelCase__						)
            torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

        A					:			Dict		=  None
        for cpu_offloaded_model in [self.unet, self.movq]:
            A					:			Any		=  cpu_offload_with_hook(lowerCamelCase__,						lowerCamelCase__,						prev_module_hook=lowerCamelCase__						)

        # We'll offload the last model manually.
        A					:			Any		=  hook






    @property
    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
    def      _lowerCAmelCase   (			self						):


        if not hasattr(self.unet,						"""_hf_hook"""						):
            return self.device
        for module in self.unet.modules():
            if (
                hasattr(lowerCamelCase__,						"""_hf_hook"""						)
                and hasattr(module._hf_hook,						"""execution_device"""						)
                and module._hf_hook.execution_device is not None
            ):
                return torch.device(module._hf_hook.execution_device						)
        return self.device






    @torch.no_grad()
    @replace_example_docstring(lowerCamelCase__						)
    def __call__(			self,						lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__ = 512,						lowerCamelCase__ = 512,						lowerCamelCase__ = 100,						lowerCamelCase__ = 4.0,						lowerCamelCase__ = 1,						lowerCamelCase__ = None,						lowerCamelCase__ = None,						lowerCamelCase__ = "pil",						lowerCamelCase__ = True,						):
        A					:			Any		=  self._execution_device

        A					:			Any		=  guidance_scale > 1.0

        if isinstance(lowerCamelCase__,						lowerCamelCase__						):
            A					:			List[Any]		=  torch.cat(lowerCamelCase__,						dim=0						)
        if isinstance(lowerCamelCase__,						lowerCamelCase__						):
            A					:			List[str]		=  torch.cat(lowerCamelCase__,						dim=0						)
        if isinstance(lowerCamelCase__,						lowerCamelCase__						):
            A					:			int		=  torch.cat(lowerCamelCase__,						dim=0						)

        A					:			Any		=  image_embeds.shape[0] * num_images_per_prompt

        if do_classifier_free_guidance:
            A					:			Optional[Any]		=  image_embeds.repeat_interleave(lowerCamelCase__,						dim=0						)
            A					:			Any		=  negative_image_embeds.repeat_interleave(lowerCamelCase__,						dim=0						)
            A					:			Optional[Any]		=  hint.repeat_interleave(lowerCamelCase__,						dim=0						)

        A					:			Union[str, Any]		=  torch.cat([negative_image_embeds, image_embeds],						dim=0						).to(dtype=self.unet.dtype,						device=lowerCamelCase__						)
        A					:			List[str]		=  torch.cat([hint, hint],						dim=0						).to(dtype=self.unet.dtype,						device=lowerCamelCase__						)
        self.scheduler.set_timesteps(lowerCamelCase__,						device=lowerCamelCase__						)
        A					:			Union[str, Any]		=  self.scheduler.timesteps

        A					:			int		=  self.movq.config.latent_channels

        A					:			Union[str, Any]		=  downscale_height_and_width(lowerCamelCase__,						lowerCamelCase__,						self.movq_scale_factor						)

        # create initial latent
        A					:			Any		=  self.prepare_latents(
            (batch_size, num_channels_latents, height, width),						image_embeds.dtype,						lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__,						self.scheduler,						)

        for i, t in enumerate(self.progress_bar(lowerCamelCase__						)						):
            # expand the latents if we are doing classifier free guidance
            A					:			Any		=  torch.cat([latents] * 2						) if do_classifier_free_guidance else latents

            A					:			Optional[int]		=  {'image_embeds': image_embeds, 'hint': hint}
            A					:			Any		=  self.unet(
                sample=lowerCamelCase__,						timestep=lowerCamelCase__,						encoder_hidden_states=lowerCamelCase__,						added_cond_kwargs=lowerCamelCase__,						return_dict=lowerCamelCase__,						)[0]

            if do_classifier_free_guidance:
                A					:			Union[str, Any]		=  noise_pred.split(latents.shape[1],						dim=1						)
                A					:			Any		=  noise_pred.chunk(2						)
                A					:			List[str]		=  variance_pred.chunk(2						)
                A					:			str		=  noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                A					:			List[str]		=  torch.cat([noise_pred, variance_pred_text],						dim=1						)

            if not (
                hasattr(self.scheduler.config,						"""variance_type"""						)
                and self.scheduler.config.variance_type in ["learned", "learned_range"]
            ):
                A					:			List[Any]		=  noise_pred.split(latents.shape[1],						dim=1						)

            # compute the previous noisy sample x_t -> x_t-1
            A					:			Dict		=  self.scheduler.step(
                lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__,						generator=lowerCamelCase__,						)[0]
        # post-processing
        A					:			Union[str, Any]		=  self.movq.decode(lowerCamelCase__,						force_not_quantize=lowerCamelCase__						)['sample']

        if output_type not in ["pt", "np", "pil"]:
            raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'''						)

        if output_type in ["np", "pil"]:
            A					:			List[str]		=  image * 0.5 + 0.5
            A					:			List[str]		=  image.clamp(0,						1						)
            A					:			List[str]		=  image.cpu().permute(0,						2,						3,						1						).float().numpy()

        if output_type == "pil":
            A					:			int		=  self.numpy_to_pil(lowerCamelCase__						)

        if not return_dict:
            return (image,)

        return ImagePipelineOutput(images=lowerCamelCase__						)







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 						lowercase    :
						'''simple docstring'''


						def __init__(  self    :				List[Any]       ,	snake_case    :				Optional[Any]       ,	snake_case    :				int=13       ,	snake_case    :				int=7       ,	snake_case    :				Dict=True       ,	snake_case    :				Union[str, Any]=True       ,	snake_case    :				Union[str, Any]=True       ,	snake_case    :				List[Any]=True       ,	snake_case    :				Tuple=99       ,	snake_case    :				Any=[1, 1, 2]       ,	snake_case    :				Dict=1       ,	snake_case    :				Optional[int]=32       ,	snake_case    :				Union[str, Any]=4       ,	snake_case    :				Optional[Any]=8       ,	snake_case    :				Dict=37       ,	snake_case    :				int="gelu_new"       ,	snake_case    :				Optional[Any]=0.1       ,	snake_case    :				List[str]=0.1       ,	snake_case    :				Any=0.0       ,	snake_case    :				Dict=512       ,	snake_case    :				List[str]=3       ,	snake_case    :				Any=0.02       ,	snake_case    :				List[str]=3       ,	snake_case    :				Optional[Any]=4       ,	snake_case    :				Dict=None       ,	snake_case    :				Any=False       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				parent
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				batch_size
											SCREAMING_SNAKE_CASE							:     List[str]						=				seq_length
											SCREAMING_SNAKE_CASE							:     int						=				is_training
											SCREAMING_SNAKE_CASE							:     Any						=				use_input_mask
											SCREAMING_SNAKE_CASE							:     Tuple						=				use_token_type_ids
											SCREAMING_SNAKE_CASE							:     Dict						=				use_labels
											SCREAMING_SNAKE_CASE							:     Dict						=				vocab_size
											SCREAMING_SNAKE_CASE							:     Dict						=				block_sizes
											SCREAMING_SNAKE_CASE							:     Dict						=				num_decoder_layers
											SCREAMING_SNAKE_CASE							:     int						=				d_model
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				n_head
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				d_head
											SCREAMING_SNAKE_CASE							:     int						=				d_inner
											SCREAMING_SNAKE_CASE							:     List[Any]						=				hidden_act
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				hidden_dropout
											SCREAMING_SNAKE_CASE							:     Any						=				attention_dropout
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				activation_dropout
											SCREAMING_SNAKE_CASE							:     str						=				max_position_embeddings
											SCREAMING_SNAKE_CASE							:     int						=				type_vocab_size
											SCREAMING_SNAKE_CASE							:     str						=				2
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				num_labels
											SCREAMING_SNAKE_CASE							:     Tuple						=				num_choices
											SCREAMING_SNAKE_CASE							:     str						=				scope
											SCREAMING_SNAKE_CASE							:     int						=				initializer_std

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







						def       lowerCamelCase_				(  self    :				int	):



											'''simple docstring'''


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

											SCREAMING_SNAKE_CASE							:     Dict						=				None
											if self.use_input_mask:
																SCREAMING_SNAKE_CASE							:     Optional[int]						=				random_attention_mask([self.batch_size, self.seq_length]	)

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

											SCREAMING_SNAKE_CASE							:     Any						=				None
											SCREAMING_SNAKE_CASE							:     Dict						=				None
											SCREAMING_SNAKE_CASE							:     int						=				None
											if self.use_labels:
																SCREAMING_SNAKE_CASE							:     List[Any]						=				ids_tensor([self.batch_size]       ,	self.type_sequence_label_size	)
																SCREAMING_SNAKE_CASE							:     Any						=				ids_tensor([self.batch_size, self.seq_length]       ,	self.num_labels	)
																SCREAMING_SNAKE_CASE							:     Dict						=				ids_tensor([self.batch_size]       ,	self.num_choices	)

											SCREAMING_SNAKE_CASE							:     Dict						=				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    :				Dict       ,	snake_case    :				List[str]       ,	snake_case    :				Tuple       ,	snake_case    :				Union[str, Any]       ,	snake_case    :				Any       ,	snake_case    :				Dict       ,	snake_case    :				Any       ,	snake_case    :				Union[str, Any]       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     List[str]						=				TFFunnelModel(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     Dict						=				{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				model(snake_case	)

											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				[input_ids, input_mask]
											SCREAMING_SNAKE_CASE							:     List[Any]						=				model(snake_case	)

											SCREAMING_SNAKE_CASE							:     int						=				model(snake_case	)
											self.parent.assertEqual(result.last_hidden_state.shape       ,	(self.batch_size, self.seq_length, self.d_model)	)

											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				False
											SCREAMING_SNAKE_CASE							:     Any						=				TFFunnelModel(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     Dict						=				model(snake_case	)
											self.parent.assertEqual(result.last_hidden_state.shape       ,	(self.batch_size, self.seq_length, self.d_model)	)

											SCREAMING_SNAKE_CASE							:     Any						=				False
											SCREAMING_SNAKE_CASE							:     int						=				TFFunnelModel(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     List[Any]						=				model(snake_case	)
											self.parent.assertEqual(result.last_hidden_state.shape       ,	(self.batch_size, self.seq_length, self.d_model)	)







						def       lowerCamelCase_				(  self    :				str       ,	snake_case    :				Any       ,	snake_case    :				Dict       ,	snake_case    :				Any       ,	snake_case    :				Optional[Any]       ,	snake_case    :				Tuple       ,	snake_case    :				Dict       ,	snake_case    :				Optional[Any]       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     str						=				TFFunnelBaseModel(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     List[str]						=				{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				model(snake_case	)

											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				[input_ids, input_mask]
											SCREAMING_SNAKE_CASE							:     Tuple						=				model(snake_case	)

											SCREAMING_SNAKE_CASE							:     Any						=				model(snake_case	)
											self.parent.assertEqual(result.last_hidden_state.shape       ,	(self.batch_size, 2, self.d_model)	)

											SCREAMING_SNAKE_CASE							:     Optional[int]						=				False
											SCREAMING_SNAKE_CASE							:     int						=				TFFunnelBaseModel(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     Any						=				model(snake_case	)
											self.parent.assertEqual(result.last_hidden_state.shape       ,	(self.batch_size, 3, self.d_model)	)

											SCREAMING_SNAKE_CASE							:     int						=				False
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				TFFunnelBaseModel(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				model(snake_case	)
											self.parent.assertEqual(result.last_hidden_state.shape       ,	(self.batch_size, 2, self.d_model)	)







						def       lowerCamelCase_				(  self    :				Optional[int]       ,	snake_case    :				Any       ,	snake_case    :				str       ,	snake_case    :				Optional[int]       ,	snake_case    :				List[str]       ,	snake_case    :				Union[str, Any]       ,	snake_case    :				List[Any]       ,	snake_case    :				Dict       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Any						=				TFFunnelForPreTraining(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     str						=				{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											SCREAMING_SNAKE_CASE							:     List[str]						=				model(snake_case	)
											self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.seq_length)	)







						def       lowerCamelCase_				(  self    :				List[str]       ,	snake_case    :				Any       ,	snake_case    :				int       ,	snake_case    :				List[str]       ,	snake_case    :				Tuple       ,	snake_case    :				int       ,	snake_case    :				str       ,	snake_case    :				List[Any]       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Dict						=				TFFunnelForMaskedLM(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     Tuple						=				{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											SCREAMING_SNAKE_CASE							:     Tuple						=				model(snake_case	)
											self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.seq_length, self.vocab_size)	)







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



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Tuple						=				self.num_labels
											SCREAMING_SNAKE_CASE							:     Any						=				TFFunnelForSequenceClassification(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     Tuple						=				{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											SCREAMING_SNAKE_CASE							:     Tuple						=				model(snake_case	)
											self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.num_labels)	)







						def       lowerCamelCase_				(  self    :				Optional[Any]       ,	snake_case    :				List[Any]       ,	snake_case    :				Optional[Any]       ,	snake_case    :				Any       ,	snake_case    :				Dict       ,	snake_case    :				Dict       ,	snake_case    :				int       ,	snake_case    :				Tuple       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Dict						=				self.num_choices
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				TFFunnelForMultipleChoice(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				tf.tile(tf.expand_dims(snake_case       ,	1	)       ,	(1, self.num_choices, 1)	)
											SCREAMING_SNAKE_CASE							:     Tuple						=				tf.tile(tf.expand_dims(snake_case       ,	1	)       ,	(1, self.num_choices, 1)	)
											SCREAMING_SNAKE_CASE							:     Tuple						=				tf.tile(tf.expand_dims(snake_case       ,	1	)       ,	(1, self.num_choices, 1)	)
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				{
											    'input_ids': multiple_choice_inputs_ids,
											    'attention_mask': multiple_choice_input_mask,
											    'token_type_ids': multiple_choice_token_type_ids,
											}
											SCREAMING_SNAKE_CASE							:     List[str]						=				model(snake_case	)
											self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.num_choices)	)







						def       lowerCamelCase_				(  self    :				Any       ,	snake_case    :				Optional[Any]       ,	snake_case    :				Dict       ,	snake_case    :				Any       ,	snake_case    :				int       ,	snake_case    :				Union[str, Any]       ,	snake_case    :				Any       ,	snake_case    :				Optional[Any]       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     int						=				self.num_labels
											SCREAMING_SNAKE_CASE							:     List[Any]						=				TFFunnelForTokenClassification(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											SCREAMING_SNAKE_CASE							:     Tuple						=				model(snake_case	)
											self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.seq_length, self.num_labels)	)







						def       lowerCamelCase_				(  self    :				str       ,	snake_case    :				Optional[Any]       ,	snake_case    :				Any       ,	snake_case    :				Dict       ,	snake_case    :				Any       ,	snake_case    :				Union[str, Any]       ,	snake_case    :				List[Any]       ,	snake_case    :				Dict       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Tuple						=				TFFunnelForQuestionAnswering(config=snake_case	)
											SCREAMING_SNAKE_CASE							:     List[str]						=				{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											SCREAMING_SNAKE_CASE							:     Dict						=				model(snake_case	)
											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    :				Optional[Any]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				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
											)					,  
											)							:     Any						=				config_and_inputs
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
											return config, inputs_dict


@require_tf
class 						lowercase    (							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_      ,    unittest.TestCase):
						'''simple docstring'''


						UpperCAmelCase			:		int		=		(
						    (
						        TFFunnelModel,
						        TFFunnelForMaskedLM,
						        TFFunnelForPreTraining,
						        TFFunnelForQuestionAnswering,
						        TFFunnelForTokenClassification,
						    )
						    if is_tf_available()
						    else ()
						)
						UpperCAmelCase			:		Optional[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 {}
						)
						UpperCAmelCase			:		Any		=		False
						UpperCAmelCase			:		Tuple		=		False







						def       lowerCamelCase_				(  self    :				str	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     int						=				TFFunnelModelTester(self	)
											SCREAMING_SNAKE_CASE							:     Any						=				ConfigTester(self       ,	config_class=snake_case	)







						def       lowerCamelCase_				(  self    :				Any	):



											'''simple docstring'''


											self.config_tester.run_common_tests()







						def       lowerCamelCase_				(  self    :				Any	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*snake_case	)







						def       lowerCamelCase_				(  self    :				str	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     str						=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_pretraining(*snake_case	)







						def       lowerCamelCase_				(  self    :				List[Any]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Tuple						=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_lm(*snake_case	)







						def       lowerCamelCase_				(  self    :				Union[str, Any]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_token_classification(*snake_case	)







						def       lowerCamelCase_				(  self    :				List[Any]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     int						=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_question_answering(*snake_case	)


@require_tf
class 						lowercase    (							SCREAMING_SNAKE_CASE_      ,    unittest.TestCase):
						'''simple docstring'''


						UpperCAmelCase			:		Any		=		(
						    (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
						)
						UpperCAmelCase			:		List[str]		=		False
						UpperCAmelCase			:		Tuple		=		False







						def       lowerCamelCase_				(  self    :				Optional[Any]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				TFFunnelModelTester(self       ,	base=snake_case	)
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				ConfigTester(self       ,	config_class=snake_case	)







						def       lowerCamelCase_				(  self    :				int	):



											'''simple docstring'''


											self.config_tester.run_common_tests()







						def       lowerCamelCase_				(  self    :				int	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     str						=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_base_model(*snake_case	)







						def       lowerCamelCase_				(  self    :				Dict	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     str						=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_sequence_classification(*snake_case	)







						def       lowerCamelCase_				(  self    :				int	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_multiple_choice(*snake_case	)