# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
# and https://github.com/hojonathanho/diffusion
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from diffusers.utils import BaseOutput, deprecate





@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
class 					A							(    UpperCamelCase__					):
			__UpperCAmelCase			:			Union[str, Any]              =      42
			__UpperCAmelCase			:			int              =      None




def        lowerCAmelCase_			(					__A,  __A=0.999,  __A="cosine",  )					->    Optional[Any]:







						'''simple docstring'''


						if alpha_transform_type == "cosine":

												def alpha_bar_fn(__A							):
																		return math.cos((t + 0.008) / 1.008 * math.pi / 2							) ** 2

						elif alpha_transform_type == "exp":

												def alpha_bar_fn(__A							):
																		return math.exp(t * -12.0							)

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

						UpperCAmelCase__								=  []
						for i in range(UpperCamelCase__							):
												UpperCAmelCase__								=  i / num_diffusion_timesteps
												UpperCAmelCase__								=  (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 					A							(    UpperCamelCase__		,    UpperCamelCase__					):
			__UpperCAmelCase			:			List[str]              =      1


			@register_to_config
			def __init__(self					:						Union[str, Any]	,  __UpperCAmelCase					:						List[str] = 1_0_0_0	,  __UpperCAmelCase					:						List[Any] = 0.0001	,  __UpperCAmelCase					:						List[Any] = 0.02	,  __UpperCAmelCase					:						Tuple = "linear"	,  __UpperCAmelCase					:						Optional[int] = None	,  __UpperCAmelCase					:						str = True	,  __UpperCAmelCase					:						str = True	,  __UpperCAmelCase					:						int = 0	,  __UpperCAmelCase					:						List[str] = "epsilon"	,  __UpperCAmelCase					:						Optional[Any] = 1.0	,  **__UpperCAmelCase					:						Union[str, Any]	,  )						->    Union[str, Any]:
									"""simple docstring"""



									if kwargs.get("set_alpha_to_one"	,  __lowerCamelCase		) is not None:
															UpperCAmelCase__								=  (
															    "The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead."
															)
															deprecate("set_alpha_to_one"	,  "1.0.0"	,  __lowerCamelCase	,  standard_warn=__lowerCamelCase		)
															UpperCAmelCase__								=  kwargs["set_alpha_to_one"]
									if trained_betas is not None:
															UpperCAmelCase__								=  torch.tensor(__lowerCamelCase	,  dtype=torch.floataa		)
									elif beta_schedule == "linear":
															UpperCAmelCase__								=  torch.linspace(__lowerCamelCase	,  __lowerCamelCase	,  __lowerCamelCase	,  dtype=torch.floataa		)
									elif beta_schedule == "scaled_linear":
															# this schedule is very specific to the latent diffusion model.
															UpperCAmelCase__								=  (
															    torch.linspace(beta_start**0.5	,  beta_end**0.5	,  __lowerCamelCase	,  dtype=torch.floataa		) ** 2
															)
									elif beta_schedule == "squaredcos_cap_v2":
															# Glide cosine schedule
															UpperCAmelCase__								=  betas_for_alpha_bar(__lowerCamelCase		)
									else:
															raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}"""		)

									UpperCAmelCase__								=  1.0 - self.betas
									UpperCAmelCase__								=  torch.cumprod(self.alphas	,  dim=0		)

									# At every step in inverted ddim, we are looking into the next alphas_cumprod
									# For the final step, there is no next alphas_cumprod, and the index is out of bounds
									# `set_alpha_to_zero` decides whether we set this parameter simply to zero
									# in this case, self.step() just output the predicted noise
									# or whether we use the final alpha of the "non-previous" one.
									UpperCAmelCase__								=  torch.tensor(0.0		) if set_alpha_to_zero else self.alphas_cumprod[-1]

									# standard deviation of the initial noise distribution
									UpperCAmelCase__								=  1.0

									# setable values
									UpperCAmelCase__								=  None
									UpperCAmelCase__								=  torch.from_numpy(np.arange(0	,  __lowerCamelCase		).copy().astype(np.intaa		)		)


			def       lowercase_				(self					:						List[str]	,  __UpperCAmelCase					:						Union[str, Any]	,  __UpperCAmelCase					:						Tuple = None		)						->    List[Any]:
									"""simple docstring"""



									return sample


			def       lowercase_				(self					:						Union[str, Any]	,  __UpperCAmelCase					:						Tuple	,  __UpperCAmelCase					:						int = None		)						->    List[str]:
									"""simple docstring"""



									if num_inference_steps > self.config.num_train_timesteps:
															raise ValueError(
															    f"""`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"""
															    f""" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"""
															    f""" maximal {self.config.num_train_timesteps} timesteps."""		)

									UpperCAmelCase__								=  num_inference_steps
									UpperCAmelCase__								=  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
									UpperCAmelCase__								=  (np.arange(0	,  __lowerCamelCase		) * step_ratio).round().copy().astype(np.intaa		)
									UpperCAmelCase__								=  torch.from_numpy(__lowerCamelCase		).to(__lowerCamelCase		)
									self.timesteps += self.config.steps_offset


			def       lowercase_				(self					:						List[Any]	,  __UpperCAmelCase					:						Tuple	,  __UpperCAmelCase					:						Tuple	,  __UpperCAmelCase					:						Dict	,  __UpperCAmelCase					:						str = 0.0	,  __UpperCAmelCase					:						str = False	,  __UpperCAmelCase					:						Optional[int] = None	,  __UpperCAmelCase					:						str = True	,  )						->    Tuple:
									"""simple docstring"""



									UpperCAmelCase__								=  timestep + self.config.num_train_timesteps // self.num_inference_steps

									# 2. compute alphas, betas
									# change original implementation to exactly match noise levels for analogous forward process
									UpperCAmelCase__								=  self.alphas_cumprod[timestep]
									UpperCAmelCase__								=  (
									    self.alphas_cumprod[prev_timestep]
									    if prev_timestep < self.config.num_train_timesteps
									    else self.final_alpha_cumprod
									)

									UpperCAmelCase__								=  1 - alpha_prod_t

									# 3. compute predicted original sample from predicted noise also called
									# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
									if self.config.prediction_type == "epsilon":
															UpperCAmelCase__								=  (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
															UpperCAmelCase__								=  model_output
									elif self.config.prediction_type == "sample":
															UpperCAmelCase__								=  model_output
															UpperCAmelCase__								=  (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
									elif self.config.prediction_type == "v_prediction":
															UpperCAmelCase__								=  (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
															UpperCAmelCase__								=  (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
									else:
															raise ValueError(
															    f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"""
															    " `v_prediction`"		)

									# 4. Clip or threshold "predicted x_0"
									if self.config.clip_sample:
															UpperCAmelCase__								=  pred_original_sample.clamp(
															    -self.config.clip_sample_range	,  self.config.clip_sample_range		)

									# 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
									UpperCAmelCase__								=  (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon

									# 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
									UpperCAmelCase__								=  alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction

									if not return_dict:
															return (prev_sample, pred_original_sample)
									return DDIMSchedulerOutput(prev_sample=__lowerCamelCase	,  pred_original_sample=__lowerCamelCase		)





			def __len__(self					:						Tuple		)						->    Any:
									"""simple docstring"""



									return self.config.num_train_timesteps




from __future__ import annotations

import unittest

from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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.models.distilbert.modeling_tf_distilbert import (
          TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFDistilBertForMaskedLM,
          TFDistilBertForMultipleChoice,
          TFDistilBertForQuestionAnswering,
          TFDistilBertForSequenceClassification,
          TFDistilBertForTokenClassification,
          TFDistilBertModel,
      )





class 					A							:


   def __init__(self					:						Tuple	,  __UpperCAmelCase					:						str	,  )						->    Dict:
         """simple docstring"""



         UpperCAmelCase__								=  parent
         UpperCAmelCase__								=  1_3
         UpperCAmelCase__								=  7
         UpperCAmelCase__								=  True
         UpperCAmelCase__								=  True
         UpperCAmelCase__								=  False
         UpperCAmelCase__								=  True
         UpperCAmelCase__								=  9_9
         UpperCAmelCase__								=  3_2
         UpperCAmelCase__								=  2
         UpperCAmelCase__								=  4
         UpperCAmelCase__								=  3_7
         UpperCAmelCase__								=  "gelu"
         UpperCAmelCase__								=  0.1
         UpperCAmelCase__								=  0.1
         UpperCAmelCase__								=  5_1_2
         UpperCAmelCase__								=  1_6
         UpperCAmelCase__								=  2
         UpperCAmelCase__								=  0.02
         UpperCAmelCase__								=  3
         UpperCAmelCase__								=  4
         UpperCAmelCase__								=  None


   def       lowercase_				(self					:						int		)						->    Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  ids_tensor([self.batch_size, self.seq_length]	,  self.vocab_size		)

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

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

         UpperCAmelCase__								=  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	,  )

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


   def       lowercase_				(self					:						int	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						Tuple	,  __UpperCAmelCase					:						Optional[Any]	,  __UpperCAmelCase					:						Union[str, Any]	,  __UpperCAmelCase					:						Tuple	,  __UpperCAmelCase					:						Tuple		)						->    Tuple:
         """simple docstring"""



         UpperCAmelCase__								=  TFDistilBertModel(config=__UpperCAmelCase		)
         UpperCAmelCase__								=  {"input_ids": input_ids, "attention_mask": input_mask}

         UpperCAmelCase__								=  model(__UpperCAmelCase		)

         UpperCAmelCase__								=  [input_ids, input_mask]

         UpperCAmelCase__								=  model(__UpperCAmelCase		)

         self.parent.assertEqual(result.last_hidden_state.shape	,  (self.batch_size, self.seq_length, self.hidden_size)		)


   def       lowercase_				(self					:						str	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						Optional[Any]	,  __UpperCAmelCase					:						Union[str, Any]	,  __UpperCAmelCase					:						List[Any]	,  __UpperCAmelCase					:						Any	,  __UpperCAmelCase					:						Dict		)						->    List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  TFDistilBertForMaskedLM(config=__UpperCAmelCase		)
         UpperCAmelCase__								=  {"input_ids": input_ids, "attention_mask": input_mask}
         UpperCAmelCase__								=  model(__UpperCAmelCase		)
         self.parent.assertEqual(result.logits.shape	,  (self.batch_size, self.seq_length, self.vocab_size)		)


   def       lowercase_				(self					:						int	,  __UpperCAmelCase					:						Dict	,  __UpperCAmelCase					:						Optional[Any]	,  __UpperCAmelCase					:						str	,  __UpperCAmelCase					:						Optional[Any]	,  __UpperCAmelCase					:						List[Any]	,  __UpperCAmelCase					:						List[str]		)						->    List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  TFDistilBertForQuestionAnswering(config=__UpperCAmelCase		)
         UpperCAmelCase__								=  {
             "input_ids": input_ids,
             "attention_mask": input_mask,
         }
         UpperCAmelCase__								=  model(__UpperCAmelCase		)
         self.parent.assertEqual(result.start_logits.shape	,  (self.batch_size, self.seq_length)		)
         self.parent.assertEqual(result.end_logits.shape	,  (self.batch_size, self.seq_length)		)


   def       lowercase_				(self					:						Optional[int]	,  __UpperCAmelCase					:						str	,  __UpperCAmelCase					:						Optional[Any]	,  __UpperCAmelCase					:						List[str]	,  __UpperCAmelCase					:						Dict	,  __UpperCAmelCase					:						Optional[int]	,  __UpperCAmelCase					:						List[str]		)						->    str:
         """simple docstring"""



         UpperCAmelCase__								=  self.num_labels
         UpperCAmelCase__								=  TFDistilBertForSequenceClassification(__UpperCAmelCase		)
         UpperCAmelCase__								=  {"input_ids": input_ids, "attention_mask": input_mask}
         UpperCAmelCase__								=  model(__UpperCAmelCase		)
         self.parent.assertEqual(result.logits.shape	,  (self.batch_size, self.num_labels)		)


   def       lowercase_				(self					:						Optional[int]	,  __UpperCAmelCase					:						List[Any]	,  __UpperCAmelCase					:						Optional[Any]	,  __UpperCAmelCase					:						Dict	,  __UpperCAmelCase					:						List[Any]	,  __UpperCAmelCase					:						str	,  __UpperCAmelCase					:						Any		)						->    int:
         """simple docstring"""



         UpperCAmelCase__								=  self.num_choices
         UpperCAmelCase__								=  TFDistilBertForMultipleChoice(__UpperCAmelCase		)
         UpperCAmelCase__								=  tf.tile(tf.expand_dims(__UpperCAmelCase	,  1		)	,  (1, self.num_choices, 1)		)
         UpperCAmelCase__								=  tf.tile(tf.expand_dims(__UpperCAmelCase	,  1		)	,  (1, self.num_choices, 1)		)
         UpperCAmelCase__								=  {
             "input_ids": multiple_choice_inputs_ids,
             "attention_mask": multiple_choice_input_mask,
         }
         UpperCAmelCase__								=  model(__UpperCAmelCase		)
         self.parent.assertEqual(result.logits.shape	,  (self.batch_size, self.num_choices)		)


   def       lowercase_				(self					:						Dict	,  __UpperCAmelCase					:						Tuple	,  __UpperCAmelCase					:						Optional[int]	,  __UpperCAmelCase					:						Tuple	,  __UpperCAmelCase					:						List[str]	,  __UpperCAmelCase					:						Any	,  __UpperCAmelCase					:						Optional[int]		)						->    List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.num_labels
         UpperCAmelCase__								=  TFDistilBertForTokenClassification(__UpperCAmelCase		)
         UpperCAmelCase__								=  {"input_ids": input_ids, "attention_mask": input_mask}
         UpperCAmelCase__								=  model(__UpperCAmelCase		)
         self.parent.assertEqual(result.logits.shape	,  (self.batch_size, self.seq_length, self.num_labels)		)





   def       lowercase_				(self					:						Any		)						->    Dict:
         """simple docstring"""



         UpperCAmelCase__								=  self.prepare_config_and_inputs()
         ((UpperCAmelCase__)		,				(UpperCAmelCase__)		,				(UpperCAmelCase__)		,				(UpperCAmelCase__)		,				(UpperCAmelCase__)		,				(UpperCAmelCase__))								=  config_and_inputs
         UpperCAmelCase__								=  {"input_ids": input_ids, "attention_mask": input_mask}
         return config, inputs_dict





@require_tf
class 					A							(    UpperCAmelCase_		,    UpperCAmelCase_		,    unittest.TestCase					):
   __UpperCAmelCase			:			Union[str, Any]              =      (
       (
           TFDistilBertModel,
           TFDistilBertForMaskedLM,
           TFDistilBertForQuestionAnswering,
           TFDistilBertForSequenceClassification,
           TFDistilBertForTokenClassification,
           TFDistilBertForMultipleChoice,
       )
       if is_tf_available()
       else None
   )
   __UpperCAmelCase			:			Optional[int]              =      (
       {
           'feature-extraction': TFDistilBertModel,
           'fill-mask': TFDistilBertForMaskedLM,
           'question-answering': TFDistilBertForQuestionAnswering,
           'text-classification': TFDistilBertForSequenceClassification,
           'token-classification': TFDistilBertForTokenClassification,
           'zero-shot': TFDistilBertForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   __UpperCAmelCase			:			Tuple              =      False
   __UpperCAmelCase			:			str              =      False


   def       lowercase_				(self					:						Union[str, Any]		)						->    str:
         """simple docstring"""



         UpperCAmelCase__								=  TFDistilBertModelTester(self		)
         UpperCAmelCase__								=  ConfigTester(self	,  config_class=__UpperCAmelCase	,  dim=3_7		)


   def       lowercase_				(self					:						Any		)						->    int:
         """simple docstring"""



         self.config_tester.run_common_tests()


   def       lowercase_				(self					:						int		)						->    int:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_distilbert_model(*__UpperCAmelCase		)


   def       lowercase_				(self					:						Optional[int]		)						->    int:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_distilbert_for_masked_lm(*__UpperCAmelCase		)


   def       lowercase_				(self					:						Any		)						->    Optional[int]:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_distilbert_for_question_answering(*__UpperCAmelCase		)


   def       lowercase_				(self					:						List[str]		)						->    str:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_distilbert_for_sequence_classification(*__UpperCAmelCase		)


   def       lowercase_				(self					:						Dict		)						->    List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_distilbert_for_multiple_choice(*__UpperCAmelCase		)


   def       lowercase_				(self					:						str		)						->    List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_distilbert_for_token_classification(*__UpperCAmelCase		)





   @slow
   def       lowercase_				(self					:						Optional[int]		)						->    Optional[int]:
         """simple docstring"""



         for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]		):
               UpperCAmelCase__								=  TFDistilBertModel.from_pretrained(__UpperCAmelCase		)
               self.assertIsNotNone(__UpperCAmelCase		)





@require_tf
class 					A							(    unittest.TestCase					):


   @slow
   def       lowercase_				(self					:						List[Any]		)						->    Dict:
         """simple docstring"""



         UpperCAmelCase__								=  TFDistilBertModel.from_pretrained("distilbert-base-uncased"		)
         UpperCAmelCase__								=  tf.constant([[0, 1, 2, 3, 4, 5]]		)
         UpperCAmelCase__								=  model(__UpperCAmelCase		)[0]

         UpperCAmelCase__								=  [1, 6, 7_6_8]
         self.assertEqual(output.shape	,  __UpperCAmelCase		)

         UpperCAmelCase__								=  tf.constant(
             [
                 [
                     [0.19261885, -0.13732955, 0.4119799],
                     [0.22150156, -0.07422661, 0.39037204],
                     [0.22756018, -0.0896414, 0.3701467],
                 ]
             ]		)
         tf.debugging.assert_near(output[:, :3, :3]	,  __UpperCAmelCase	,  atol=1E-4		)



