

'''simple docstring'''



from typing import Callable, List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModel, CLIPTokenizer

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


__snake_case			:     List[Any]										=      logging.get_logger(__name__)  # pylint: disable=invalid-name



class lowerCamelCase			(  lowercase_	,						lowercase_						):



			'''simple docstring'''






			@register_to_config
			def __init__(				self	:						List[Any]		,      lowerCAmelCase_	:						bool		,      lowerCAmelCase_	:						Optional[int] = None		,      lowerCAmelCase_	:						Optional[int] = None			)      ->		Optional[int]:





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

									A__					:       Tuple     =learnable

									if self.learnable:
															assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
															assert length is not None, "learnable=True requires `length` to be set"

															A__					:       List[Any]     =torch.zeros(lowerCAmelCase_		,      lowerCAmelCase_			)
									else:
															A__					:       Tuple     =None

									A__					:       int     =torch.nn.Parameter(lowerCAmelCase_			)



class lowerCamelCase			(  lowercase_						):



			'''simple docstring'''






			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42


			def __init__(				self	:						List[str]		,      lowerCAmelCase_	:						VQModel		,      lowerCAmelCase_	:						CLIPTextModel		,      lowerCAmelCase_	:						CLIPTokenizer		,      lowerCAmelCase_	:						TransformeraDModel		,      lowerCAmelCase_	:						VQDiffusionScheduler		,      lowerCAmelCase_	:						LearnedClassifierFreeSamplingEmbeddings		,      )      ->		Any:





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

									self.register_modules(
									    vqvae=lowerCAmelCase_		,      transformer=lowerCAmelCase_		,      text_encoder=lowerCAmelCase_		,      tokenizer=lowerCAmelCase_		,      scheduler=lowerCAmelCase_		,      learned_classifier_free_sampling_embeddings=lowerCAmelCase_		,      )


			def lowercase__						(				self	:						int		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Union[str, Any]			)      ->		Tuple:





									'''simple docstring'''
									A__					:       str     =len(lowerCAmelCase_			) if isinstance(lowerCAmelCase_		,      lowerCAmelCase_			) else 1

									# get prompt text embeddings
									A__					:       str     =self.tokenizer(
									    lowerCAmelCase_		,      padding="""max_length"""		,      max_length=self.tokenizer.model_max_length		,      return_tensors="""pt"""		,      )
									A__					:       List[Any]     =text_inputs.input_ids

									if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
															A__					:       Tuple     =self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]			)
															logger.warning(
															    """The following part of your input was truncated because CLIP can only handle sequences up to"""
															    f" {self.tokenizer.model_max_length} tokens: {removed_text}"			)
															A__					:       List[str]     =text_input_ids[:, : self.tokenizer.model_max_length]
									A__					:       Any     =self.text_encoder(text_input_ids.to(self.device			)			)[0]

									# NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
									# While CLIP does normalize the pooled output of the text transformer when combining
									# the image and text embeddings, CLIP does not directly normalize the last hidden state.
									#
									# CLIP normalizing the pooled output.
									# https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
									A__					:       Union[str, Any]     =prompt_embeds / prompt_embeds.norm(dim=-1		,      keepdim=lowerCAmelCase_			)

									# duplicate text embeddings for each generation per prompt
									A__					:       Tuple     =prompt_embeds.repeat_interleave(lowerCAmelCase_		,      dim=0			)

									if do_classifier_free_guidance:
															if self.learned_classifier_free_sampling_embeddings.learnable:
																					A__					:       Optional[int]     =self.learned_classifier_free_sampling_embeddings.embeddings
																					A__					:       List[Any]     =negative_prompt_embeds.unsqueeze(0			).repeat(lowerCAmelCase_		,      1		,      1			)
															else:
																					A__					:       Optional[int]     =[""""""] * batch_size

																					A__					:       Optional[int]     =text_input_ids.shape[-1]
																					A__					:       List[Any]     =self.tokenizer(
																					    lowerCAmelCase_		,      padding="""max_length"""		,      max_length=lowerCAmelCase_		,      truncation=lowerCAmelCase_		,      return_tensors="""pt"""		,      )
																					A__					:       Union[str, Any]     =self.text_encoder(uncond_input.input_ids.to(self.device			)			)[0]
																					# See comment for normalizing text embeddings
																					A__					:       List[Any]     =negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1		,      keepdim=lowerCAmelCase_			)

															# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
															A__					:       Optional[Any]     =negative_prompt_embeds.shape[1]
															A__					:       List[str]     =negative_prompt_embeds.repeat(1		,      lowerCAmelCase_		,      1			)
															A__					:       int     =negative_prompt_embeds.view(batch_size * num_images_per_prompt		,      lowerCAmelCase_		,      -1			)

															# For classifier free guidance, we need to do two forward passes.
															# Here we concatenate the unconditional and text embeddings into a single batch
															# to avoid doing two forward passes
															A__					:       List[str]     =torch.cat([negative_prompt_embeds, prompt_embeds]			)

									return prompt_embeds


			@torch.no_grad()
			def __call__(				self	:						List[Any]		,      lowerCAmelCase_	:						Union[str, List[str]]		,      lowerCAmelCase_	:						int = 1_00		,      lowerCAmelCase_	:						float = 5.0		,      lowerCAmelCase_	:						float = 1.0		,      lowerCAmelCase_	:						int = 1		,      lowerCAmelCase_	:						Optional[Union[torch.Generator, List[torch.Generator]]] = None		,      lowerCAmelCase_	:						Optional[torch.FloatTensor] = None		,      lowerCAmelCase_	:						Optional[str] = "pil"		,      lowerCAmelCase_	:						bool = True		,      lowerCAmelCase_	:						Optional[Callable[[int, int, torch.FloatTensor], None]] = None		,      lowerCAmelCase_	:						int = 1		,      )      ->		Union[ImagePipelineOutput, Tuple]:





									'''simple docstring'''
									if isinstance(lowerCAmelCase_		,      lowerCAmelCase_			):
															A__					:       str     =1
									elif isinstance(lowerCAmelCase_		,      lowerCAmelCase_			):
															A__					:       List[Any]     =len(lowerCAmelCase_			)
									else:
															raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase_			)}"			)

									A__					:       Union[str, Any]     =batch_size * num_images_per_prompt

									A__					:       Dict     =guidance_scale > 1.0

									A__					:       Tuple     =self._encode_prompt(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)

									if (callback_steps is None) or (
									    callback_steps is not None and (not isinstance(lowerCAmelCase_		,      lowerCAmelCase_			) or callback_steps <= 0)
									):
															raise ValueError(
															    f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
															    f" {type(lowerCAmelCase_			)}."			)

									# get the initial completely masked latents unless the user supplied it

									A__					:       Dict     =(batch_size, self.transformer.num_latent_pixels)
									if latents is None:
															A__					:       str     =self.transformer.num_vector_embeds - 1
															A__					:       Dict     =torch.full(lowerCAmelCase_		,      lowerCAmelCase_			).to(self.device			)
									else:
															if latents.shape != latents_shape:
																					raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}"			)
															if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
																					raise ValueError(
																					    """Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,"""
																					    f" {self.transformer.num_vector_embeds - 1} (inclusive)."			)
															A__					:       List[str]     =latents.to(self.device			)

									# set timesteps
									self.scheduler.set_timesteps(lowerCAmelCase_		,      device=self.device			)

									A__					:       Any     =self.scheduler.timesteps.to(self.device			)

									A__					:       Optional[Any]     =latents

									for i, t in enumerate(self.progress_bar(lowerCAmelCase_			)			):
															# expand the sample if we are doing classifier free guidance
															A__					:       List[str]     =torch.cat([sample] * 2			) if do_classifier_free_guidance else sample

															# predict the un-noised image
															# model_output == `log_p_x_0`
															A__					:       Tuple     =self.transformer(lowerCAmelCase_		,      encoder_hidden_states=lowerCAmelCase_		,      timestep=lowerCAmelCase_			).sample

															if do_classifier_free_guidance:
																					A__					:       Union[str, Any]     =model_output.chunk(2			)
																					A__					:       int     =model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
																					model_output -= torch.logsumexp(lowerCAmelCase_		,      dim=1		,      keepdim=lowerCAmelCase_			)

															A__					:       Union[str, Any]     =self.truncate(lowerCAmelCase_		,      lowerCAmelCase_			)

															# remove `log(0)`'s (`-inf`s)
															A__					:       Dict     =model_output.clamp(-70			)

															# compute the previous noisy sample x_t -> x_t-1
															A__					:       Any     =self.scheduler.step(lowerCAmelCase_		,      timestep=lowerCAmelCase_		,      sample=lowerCAmelCase_		,      generator=lowerCAmelCase_			).prev_sample

															# call the callback, if provided
															if callback is not None and i % callback_steps == 0:
																					callback(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)

									A__					:       List[str]     =self.vqvae.config.vq_embed_dim
									A__					:       List[str]     =(batch_size, self.transformer.height, self.transformer.width, embedding_channels)
									A__					:       Dict     =self.vqvae.quantize.get_codebook_entry(lowerCAmelCase_		,      shape=lowerCAmelCase_			)
									A__					:       Any     =self.vqvae.decode(lowerCAmelCase_		,      force_not_quantize=lowerCAmelCase_			).sample

									A__					:       str     =(image / 2 + 0.5).clamp(0		,      1			)
									A__					:       Union[str, Any]     =image.cpu().permute(0		,      2		,      3		,      1			).numpy()

									if output_type == "pil":
															A__					:       Optional[int]     =self.numpy_to_pil(lowerCAmelCase_			)

									if not return_dict:
															return (image,)

									return ImagePipelineOutput(images=lowerCAmelCase_			)



			def lowercase__						(				self	:						Dict		,      lowerCAmelCase_	:						torch.FloatTensor		,      lowerCAmelCase_	:						float			)      ->		torch.FloatTensor:





									'''simple docstring'''
									A__					:       List[str]     =torch.sort(lowerCAmelCase_		,      1		,      descending=lowerCAmelCase_			)
									A__					:       Union[str, Any]     =torch.exp(lowerCAmelCase_			)
									A__					:       List[str]     =sorted_p_x_0.cumsum(dim=1			) < truncation_rate

									# Ensure that at least the largest probability is not zeroed out
									A__					:       str     =torch.full_like(keep_mask[:, 0:1, :]		,      lowerCAmelCase_			)
									A__					:       Dict     =torch.cat((all_true, keep_mask)		,      dim=1			)
									A__					:       Tuple     =keep_mask[:, :-1, :]

									A__					:       Optional[int]     =keep_mask.gather(1		,      indices.argsort(1			)			)

									A__					:       Optional[int]     =log_p_x_0.clone()

									A__					:       str     =-torch.inf  # -inf = log(0)

									return rv




'''simple docstring'''



import os
import tempfile
import unittest

from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import (
		    DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    DistilBertForMaskedLM,
		    DistilBertForMultipleChoice,
		    DistilBertForQuestionAnswering,
		    DistilBertForSequenceClassification,
		    DistilBertForTokenClassification,
		    DistilBertModel,
		)



class lowerCamelCase			(  lowercase_						):



			'''simple docstring'''






			def __init__(				self	:						Dict		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						List[str]=13		,      lowerCAmelCase_	:						Dict=7		,      lowerCAmelCase_	:						Union[str, Any]=True		,      lowerCAmelCase_	:						str=True		,      lowerCAmelCase_	:						int=False		,      lowerCAmelCase_	:						int=True		,      lowerCAmelCase_	:						int=99		,      lowerCAmelCase_	:						str=32		,      lowerCAmelCase_	:						str=5		,      lowerCAmelCase_	:						List[Any]=4		,      lowerCAmelCase_	:						Dict=37		,      lowerCAmelCase_	:						Optional[Any]="gelu"		,      lowerCAmelCase_	:						Tuple=0.1		,      lowerCAmelCase_	:						Dict=0.1		,      lowerCAmelCase_	:						str=5_12		,      lowerCAmelCase_	:						Dict=16		,      lowerCAmelCase_	:						Any=2		,      lowerCAmelCase_	:						Dict=0.02		,      lowerCAmelCase_	:						Optional[int]=3		,      lowerCAmelCase_	:						List[Any]=4		,      lowerCAmelCase_	:						Optional[int]=None		,      )      ->		List[str]:





									'''simple docstring'''
									A__					:       List[str]     =parent
									A__					:       Optional[Any]     =batch_size
									A__					:       List[Any]     =seq_length
									A__					:       Tuple     =is_training
									A__					:       Optional[int]     =use_input_mask
									A__					:       Optional[int]     =use_token_type_ids
									A__					:       Tuple     =use_labels
									A__					:       Dict     =vocab_size
									A__					:       Optional[Any]     =hidden_size
									A__					:       Tuple     =num_hidden_layers
									A__					:       Tuple     =num_attention_heads
									A__					:       Union[str, Any]     =intermediate_size
									A__					:       Dict     =hidden_act
									A__					:       List[Any]     =hidden_dropout_prob
									A__					:       Optional[int]     =attention_probs_dropout_prob
									A__					:       List[str]     =max_position_embeddings
									A__					:       str     =type_vocab_size
									A__					:       Union[str, Any]     =type_sequence_label_size
									A__					:       Tuple     =initializer_range
									A__					:       List[Any]     =num_labels
									A__					:       str     =num_choices
									A__					:       Union[str, Any]     =scope


			def lowercase__						(				self	:						int			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Dict     =ids_tensor([self.batch_size, self.seq_length]		,      self.vocab_size			)

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

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

									A__					:       str     =self.get_config()

									return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels


			def lowercase__						(				self	:						Tuple			)      ->		List[Any]:





									'''simple docstring'''
									return DistilBertConfig(
									    vocab_size=self.vocab_size		,      dim=self.hidden_size		,      n_layers=self.num_hidden_layers		,      n_heads=self.num_attention_heads		,      hidden_dim=self.intermediate_size		,      hidden_act=self.hidden_act		,      dropout=self.hidden_dropout_prob		,      attention_dropout=self.attention_probs_dropout_prob		,      max_position_embeddings=self.max_position_embeddings		,      initializer_range=self.initializer_range		,      )


			def lowercase__						(				self	:						Optional[Any]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						List[Any]			)      ->		str:





									'''simple docstring'''
									A__					:       Union[str, Any]     =DistilBertModel(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Dict     =model(lowerCAmelCase_		,      lowerCAmelCase_			)
									A__					:       List[str]     =model(lowerCAmelCase_			)
									self.parent.assertEqual(result.last_hidden_state.shape		,      (self.batch_size, self.seq_length, self.hidden_size)			)


			def lowercase__						(				self	:						Tuple		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						Any			)      ->		List[str]:





									'''simple docstring'''
									A__					:       Union[str, Any]     =DistilBertForMaskedLM(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Union[str, Any]     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length, self.vocab_size)			)


			def lowercase__						(				self	:						Dict		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						Optional[Any]			)      ->		Dict:





									'''simple docstring'''
									A__					:       Dict     =DistilBertForQuestionAnswering(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Tuple     =model(
									    lowerCAmelCase_		,      attention_mask=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 lowercase__						(				self	:						Optional[int]		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Optional[Any]		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Dict			)      ->		Tuple:





									'''simple docstring'''
									A__					:       List[Any]     =self.num_labels
									A__					:       Dict     =DistilBertForSequenceClassification(lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Union[str, Any]     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)			)


			def lowercase__						(				self	:						str		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						List[Any]			)      ->		int:





									'''simple docstring'''
									A__					:       Optional[int]     =self.num_labels
									A__					:       Union[str, Any]     =DistilBertForTokenClassification(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()

									A__					:       List[Any]     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length, self.num_labels)			)


			def lowercase__						(				self	:						Union[str, Any]		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						Optional[int]			)      ->		Dict:





									'''simple docstring'''
									A__					:       int     =self.num_choices
									A__					:       Tuple     =DistilBertForMultipleChoice(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       int     =input_ids.unsqueeze(1			).expand(-1		,      self.num_choices		,      -1			).contiguous()
									A__					:       int     =input_mask.unsqueeze(1			).expand(-1		,      self.num_choices		,      -1			).contiguous()
									A__					:       Tuple     =model(
									    lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_		,      )
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_choices)			)



			def lowercase__						(				self	:						Tuple			)      ->		Optional[Any]:





									'''simple docstring'''
									A__					:       Optional[Any]     =self.prepare_config_and_inputs()
									((A__)   ,						(A__)   ,						(A__)   ,						(A__)   ,						(A__)   ,						(A__))					:       List[str]     =config_and_inputs
									A__					:       str     ={"""input_ids""": input_ids, """attention_mask""": input_mask}
									return config, inputs_dict



@require_torch
class lowerCamelCase			(  lowercase_	,						lowercase_	,						unittest.TestCase						):



			'''simple docstring'''






			__snake_case        =	(
			    (
			        DistilBertModel,
			        DistilBertForMaskedLM,
			        DistilBertForMultipleChoice,
			        DistilBertForQuestionAnswering,
			        DistilBertForSequenceClassification,
			        DistilBertForTokenClassification,
			    )
			    if is_torch_available()
			    else None
			)
			__snake_case        =	(
			    {
			        'feature-extraction': DistilBertModel,
			        'fill-mask': DistilBertForMaskedLM,
			        'question-answering': DistilBertForQuestionAnswering,
			        'text-classification': DistilBertForSequenceClassification,
			        'token-classification': DistilBertForTokenClassification,
			        'zero-shot': DistilBertForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			__snake_case        =	True
			__snake_case        =	True
			__snake_case        =	True
			__snake_case        =	True


			def lowercase__						(				self	:						List[Any]			)      ->		Any:





									'''simple docstring'''
									A__					:       Any     =DistilBertModelTester(self			)
									A__					:       Tuple     =ConfigTester(self		,      config_class=lowerCAmelCase_		,      dim=37			)


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





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


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





									'''simple docstring'''
									A__					:       int     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_model(*lowerCAmelCase_			)


			def lowercase__						(				self	:						Any			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Tuple     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_masked_lm(*lowerCAmelCase_			)


			def lowercase__						(				self	:						List[Any]			)      ->		str:





									'''simple docstring'''
									A__					:       str     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_question_answering(*lowerCAmelCase_			)


			def lowercase__						(				self	:						List[Any]			)      ->		List[str]:





									'''simple docstring'''
									A__					:       Any     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowerCAmelCase_			)


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





									'''simple docstring'''
									A__					:       Dict     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_token_classification(*lowerCAmelCase_			)


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





									'''simple docstring'''
									A__					:       List[Any]     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowerCAmelCase_			)


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





									'''simple docstring'''
									for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															A__					:       Optional[int]     =DistilBertModel.from_pretrained(lowerCAmelCase_			)
															self.assertIsNotNone(lowerCAmelCase_			)



			@slow
			@require_torch_gpu
			def lowercase__						(				self	:						Tuple			)      ->		Any:





									'''simple docstring'''
									A__   ,						A__					:       List[str]     =self.model_tester.prepare_config_and_inputs_for_common()
									for model_class in self.all_model_classes:
															# BertForMultipleChoice behaves incorrectly in JIT environments.
															if model_class == DistilBertForMultipleChoice:
																					return

															A__					:       Any     =True
															A__					:       Optional[Any]     =model_class(config=lowerCAmelCase_			)

															A__					:       Dict     =self._prepare_for_class(lowerCAmelCase_		,      lowerCAmelCase_			)
															A__					:       Optional[int]     =torch.jit.trace(
															    lowerCAmelCase_		,      (inputs_dict["""input_ids"""].to("""cpu"""			), inputs_dict["""attention_mask"""].to("""cpu"""			))			)

															with tempfile.TemporaryDirectory() as tmp:
																					torch.jit.save(lowerCAmelCase_		,      os.path.join(lowerCAmelCase_		,      """traced_model.pt"""			)			)
																					A__					:       List[Any]     =torch.jit.load(os.path.join(lowerCAmelCase_		,      """traced_model.pt"""			)		,      map_location=lowerCAmelCase_			)
																					loaded(inputs_dict["""input_ids"""].to(lowerCAmelCase_			)		,      inputs_dict["""attention_mask"""].to(lowerCAmelCase_			)			)



@require_torch
class lowerCamelCase			(  unittest.TestCase						):



			'''simple docstring'''






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





									'''simple docstring'''
									A__					:       List[str]     =DistilBertModel.from_pretrained("""distilbert-base-uncased"""			)
									A__					:       Optional[Any]     =torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]]			)
									A__					:       int     =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]			)
									with torch.no_grad():
															A__					:       Any     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_			)[0]
									A__					:       Tuple     =torch.Size((1, 11, 7_68)			)
									self.assertEqual(output.shape		,      lowerCAmelCase_			)
									A__					:       Optional[int]     =torch.tensor(
									    [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]			)

									self.assertTrue(torch.allclose(output[:, 1:4, 1:4]		,      lowerCAmelCase_		,      atol=1e-4			)			)

