
"""simple docstring"""




from __future__ import annotations

import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import numpy
   import tensorflow as tf

   from transformers.models.esm.modeling_tf_esm import (
       TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
       TFEsmForMaskedLM,
       TFEsmForSequenceClassification,
       TFEsmForTokenClassification,
       TFEsmModel,
   )

class 		a__						:
   def __init__(			self	,    _a	,    ):
          lowercase    :				Tuple       		=							parent
          lowercase    :				List[Any]       		=							13
          lowercase    :				Any       		=							7
          lowercase    :				int       		=							True
          lowercase    :				Tuple       		=							True
          lowercase    :				Optional[Any]       		=							True
          lowercase    :				Dict       		=							99
          lowercase    :				int       		=							32
          lowercase    :				str       		=							2
          lowercase    :				Dict       		=							4
          lowercase    :				Optional[Any]       		=							37
          lowercase    :				Union[str, Any]       		=							"gelu"
          lowercase    :				Optional[Any]       		=							0.1
          lowercase    :				Union[str, Any]       		=							0.1
          lowercase    :				Tuple       		=							512
          lowercase    :				Optional[int]       		=							16
          lowercase    :				int       		=							2
          lowercase    :				Any       		=							0.0_2
          lowercase    :				Dict       		=							3
          lowercase    :				Union[str, Any]       		=							4
          lowercase    :				Union[str, Any]       		=							None
   def 			__magic_name__			(			self				):
          lowercase    :				Any       		=							ids_tensor([self.batch_size, self.seq_length]	,    self.vocab_size				)

          lowercase    :				Tuple       		=							None
          if self.use_input_mask:
                 lowercase    :				int       		=							random_attention_mask([self.batch_size, self.seq_length]				)

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

          lowercase    :				Union[str, Any]       		=							EsmConfig(
              vocab_size=self.vocab_size	,    hidden_size=self.hidden_size	,    num_hidden_layers=self.num_hidden_layers	,    pad_token_id=1	,    num_attention_heads=self.num_attention_heads	,    intermediate_size=self.intermediate_size	,    hidden_act=self.hidden_act	,    hidden_dropout_prob=self.hidden_dropout_prob	,    attention_probs_dropout_prob=self.attention_probs_dropout_prob	,    max_position_embeddings=self.max_position_embeddings	,    type_vocab_size=self.type_vocab_size	,    initializer_range=self.initializer_range	,    )

          return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
   def 			__magic_name__			(			self				):
          (
              (
              lowercase      
          )		,    (
              lowercase      
          )		,    (
              lowercase      
          )		,    (
              lowercase      
          )		,    (
              lowercase      
          )		,    (
              lowercase      
          )		,          
          )    :				str       		=							self.prepare_config_and_inputs()

          lowercase    :				int       		=							True
          lowercase    :				Union[str, Any]       		=							floats_tensor([self.batch_size, self.seq_length, self.hidden_size]				)
          lowercase    :				Any       		=							ids_tensor([self.batch_size, self.seq_length]	,    vocab_size=2				)

          return (
              config,
              input_ids,
              input_mask,
              sequence_labels,
              token_labels,
              choice_labels,
              encoder_hidden_states,
              encoder_attention_mask,
          )
   def 			__magic_name__			(			self	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a				):
          lowercase    :				List[Any]       		=							TFEsmModel(config=__UpperCAmelCase				)
          lowercase    :				List[str]       		=							{"input_ids": input_ids, "attention_mask": input_mask}
          lowercase    :				Optional[int]       		=							model(__UpperCAmelCase				)

          lowercase    :				int       		=							[input_ids, input_mask]
          lowercase    :				Dict       		=							model(__UpperCAmelCase				)

          lowercase    :				List[str]       		=							model(__UpperCAmelCase				)

          self.parent.assertEqual(result.last_hidden_state.shape	,    (self.batch_size, self.seq_length, self.hidden_size)				)
   def 			__magic_name__			(			self	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    ):
          lowercase    :				List[Any]       		=							True

          lowercase    :				List[Any]       		=							TFEsmModel(config=__UpperCAmelCase				)
          lowercase    :				int       		=							{
              "input_ids": input_ids,
              "attention_mask": input_mask,
              "encoder_hidden_states": encoder_hidden_states,
              "encoder_attention_mask": encoder_attention_mask,
          }
          lowercase    :				Optional[Any]       		=							model(__UpperCAmelCase				)

          lowercase    :				List[Any]       		=							[input_ids, input_mask]
          lowercase    :				Optional[Any]       		=							model(__UpperCAmelCase	,    encoder_hidden_states=__UpperCAmelCase				)

          # Also check the case where encoder outputs are not passed
          lowercase    :				List[str]       		=							model(__UpperCAmelCase	,    attention_mask=__UpperCAmelCase				)

          self.parent.assertEqual(result.last_hidden_state.shape	,    (self.batch_size, self.seq_length, self.hidden_size)				)
   def 			__magic_name__			(			self	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a				):
          lowercase    :				Optional[int]       		=							TFEsmForMaskedLM(config=__UpperCAmelCase				)
          lowercase    :				str       		=							model([input_ids, input_mask]				)
          self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.seq_length, self.vocab_size)				)
   def 			__magic_name__			(			self	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a				):
          lowercase    :				Any       		=							self.num_labels
          lowercase    :				Optional[Any]       		=							TFEsmForTokenClassification(config=__UpperCAmelCase				)
          lowercase    :				Any       		=							{"input_ids": input_ids, "attention_mask": input_mask}
          lowercase    :				Tuple       		=							model(__UpperCAmelCase				)
          self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.seq_length, self.num_labels)				)

   def 			__magic_name__			(			self				):
          lowercase    :				List[Any]       		=							self.prepare_config_and_inputs()
          (
              (
              lowercase      
          )		,    (
              lowercase      
          )		,    (
              lowercase      
          )		,    (
              lowercase      
          )		,    (
              lowercase      
          )		,    (
              lowercase      
          )		,          
          )    :				str       		=							config_and_inputs
          lowercase    :				Union[str, Any]       		=							{"input_ids": input_ids, "attention_mask": input_mask}
          return config, inputs_dict


@require_tf
class 		a__						(      UpperCAmelCase_,			UpperCAmelCase_,			unittest.TestCase						):
   __lowerCAmelCase            =				(
       (
           TFEsmModel,
           TFEsmForMaskedLM,
           TFEsmForSequenceClassification,
           TFEsmForTokenClassification,
       )
       if is_tf_available()
       else ()
   )
   __lowerCAmelCase            =				(
       {
           'feature-extraction': TFEsmModel,
           'fill-mask': TFEsmForMaskedLM,
           'text-classification': TFEsmForSequenceClassification,
           'token-classification': TFEsmForTokenClassification,
           'zero-shot': TFEsmForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   __lowerCAmelCase            =				False
   __lowerCAmelCase            =				False
   def 			__magic_name__			(			self				):
          lowercase    :				List[Any]       		=							TFEsmModelTester(self				)
          lowercase    :				Dict       		=							ConfigTester(self	,    config_class=__UpperCAmelCase	,    hidden_size=37				)
   def 			__magic_name__			(			self				):
          self.config_tester.run_common_tests()
   def 			__magic_name__			(			self				):
          lowercase    :				List[str]       		=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__UpperCAmelCase				)
   def 			__magic_name__			(			self				):
          lowercase    :				Union[str, Any]       		=							self.model_tester.prepare_config_and_inputs_for_decoder()
          self.model_tester.create_and_check_model_as_decoder(*__UpperCAmelCase				)
   def 			__magic_name__			(			self				):
          lowercase    :				Any       		=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase				)
   def 			__magic_name__			(			self				):
          lowercase    :				List[str]       		=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase				)
   @slow
   def 			__magic_name__			(			self				):



          for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowercase    :				Optional[Any]       		=							TFEsmModel.from_pretrained(__UpperCAmelCase				)
                 self.assertIsNotNone(__UpperCAmelCase				)
   @unittest.skip("Protein models do not support embedding resizing."				)
   def 			__magic_name__			(			self				):
          pass
   @unittest.skip("Protein models do not support embedding resizing."				)
   def 			__magic_name__			(			self				):
          pass

   def 			__magic_name__			(			self				):
          lowercase		,    lowercase    :				List[Any]       		=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 lowercase    :				Any       		=							model_class(__UpperCAmelCase				)
                 assert isinstance(model.get_input_embeddings()	,    tf.keras.layers.Layer				)
                 if model_class is TFEsmForMaskedLM:
                        # Output embedding test differs from the main test because they're a matrix, not a layer
                        lowercase    :				List[str]       		=							model.get_bias()
                        assert isinstance(__UpperCAmelCase	,    __UpperCAmelCase				)
                        for k, v in name.items():
                               assert isinstance(__UpperCAmelCase	,    tf.Variable				)
                 else:
                        lowercase    :				Tuple       		=							model.get_output_embeddings()
                        assert x is None
                        lowercase    :				int       		=							model.get_bias()
                        assert name is None


@require_tf
class 		a__						(      unittest.TestCase						):
   @slow
   def 			__magic_name__			(			self				):
          lowercase    :				Union[str, Any]       		=							TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D"				)

          lowercase    :				Optional[int]       		=							tf.constant([[0, 1, 2, 3, 4, 5]]				)
          lowercase    :				Any       		=							model(__UpperCAmelCase				)[0]
          lowercase    :				str       		=							[1, 6, 33]
          self.assertEqual(list(output.numpy().shape				)	,    __UpperCAmelCase				)
          # compare the actual values for a slice.
          lowercase    :				Union[str, Any]       		=							tf.constant(
              [
                  [
                      [8.9_2_1_5_1_8, -1_0.5_8_9_8_1_4, -6.4_6_7_1_3_0_7],
                      [-6.3_9_6_7_1_5_6, -1_3.9_1_1_3_7_7, -1.1_2_1_1_9_1_5],
                      [-7.7_8_1_2_4_7, -1_3.9_5_1_5_5_7, -3.7_4_0_5_9_2],
                  ]
              ]				)
          self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()	,    expected_slice.numpy()	,    atol=1E-2				)				)

   @slow
   def 			__magic_name__			(			self				):
          lowercase    :				Union[str, Any]       		=							TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D"				)

          lowercase    :				Union[str, Any]       		=							tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]				)
          lowercase    :				int       		=							model(__UpperCAmelCase				)[0]
          # compare the actual values for a slice.
          lowercase    :				Dict       		=							tf.constant(
              [
                  [
                      [0.1_4_4_4_3_0_9_2, 0.5_4_1_2_5_3_2_7, 0.3_2_4_7_7_3_9],
                      [0.3_0_3_4_0_4_8_4, 0.0_0_5_2_6_6_7_6, 0.3_1_0_7_7_7_2_2],
                      [0.3_2_2_7_8_0_4_3, -0.2_4_9_8_7_0_9_6, 0.3_4_1_4_6_2_8],
                  ]
              ]				)
          self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()	,    expected_slice.numpy()	,    atol=1E-4				)				)



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

import numpy as np
import torch

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





@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP
class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : torch.FloatTensor
   __UpperCAmelCase : Optional[torch.FloatTensor]      =			None




def    lowerCAmelCase_ (     __A,  __A=0.999,  __A="cosine",  )     ->				Tuple:







      '''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(__A							):
            UpperCAmelCase__								=  i / num_diffusion_timesteps
            UpperCAmelCase__								=  (i + 1) / num_diffusion_timesteps
            betas.append(min(1 - alpha_bar_fn(__A							) / alpha_bar_fn(__A							),  __A							)							)
      return torch.tensor(__A,  dtype=torch.floataa							)







class      A							(				UpperCAmelCase_		,				UpperCAmelCase_     ):


   @register_to_config
   def __init__(self     :						List[str]       ,  __UpperCAmelCase     :						int = 1_0_0_0       ,  __UpperCAmelCase     :						str = "fixed_small_log"       ,  __UpperCAmelCase     :						bool = True       ,  __UpperCAmelCase     :						Optional[float] = 1.0       ,  __UpperCAmelCase     :						str = "epsilon"       ,  __UpperCAmelCase     :						str = "squaredcos_cap_v2"       ,  )						->				Optional[int]:
         """simple docstring"""



         if beta_schedule != "squaredcos_cap_v2":
               raise ValueError("UnCLIPScheduler only supports `beta_schedule`: 'squaredcos_cap_v2'"		)

         UpperCAmelCase__								=  betas_for_alpha_bar(__UpperCAmelCase		)

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

         # standard deviation of the initial noise distribution
         UpperCAmelCase__								=  1.0

         # setable values
         UpperCAmelCase__								=  None
         UpperCAmelCase__								=  torch.from_numpy(np.arange(0       ,  __UpperCAmelCase		)[::-1].copy()		)

         UpperCAmelCase__								=  variance_type


   def 			lowercase_      (self     :						List[str]       ,  __UpperCAmelCase     :						torch.FloatTensor       ,  __UpperCAmelCase     :						Optional[int] = None		)						->				torch.FloatTensor:
         """simple docstring"""



         return sample


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



         UpperCAmelCase__								=  num_inference_steps
         UpperCAmelCase__								=  (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1)
         UpperCAmelCase__								=  (np.arange(0       ,  __UpperCAmelCase		) * step_ratio).round()[::-1].copy().astype(np.intaa		)
         UpperCAmelCase__								=  torch.from_numpy(__UpperCAmelCase		).to(__UpperCAmelCase		)


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



         if prev_timestep is None:
               UpperCAmelCase__								=  t - 1

         UpperCAmelCase__								=  self.alphas_cumprod[t]
         UpperCAmelCase__								=  self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one
         UpperCAmelCase__								=  1 - alpha_prod_t
         UpperCAmelCase__								=  1 - alpha_prod_t_prev

         if prev_timestep == t - 1:
               UpperCAmelCase__								=  self.betas[t]
         else:
               UpperCAmelCase__								=  1 - alpha_prod_t / alpha_prod_t_prev

         # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf)
         # and sample from it to get previous sample
         # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample
         UpperCAmelCase__								=  beta_prod_t_prev / beta_prod_t * beta

         if variance_type is None:
               UpperCAmelCase__								=  self.config.variance_type

         # hacks - were probably added for training stability
         if variance_type == "fixed_small_log":
               UpperCAmelCase__								=  torch.log(torch.clamp(__UpperCAmelCase       ,  min=1E-20		)		)
               UpperCAmelCase__								=  torch.exp(0.5 * variance		)
         elif variance_type == "learned_range":
               # NOTE difference with DDPM scheduler
               UpperCAmelCase__								=  variance.log()
               UpperCAmelCase__								=  beta.log()

               UpperCAmelCase__								=  (predicted_variance + 1) / 2
               UpperCAmelCase__								=  frac * max_log + (1 - frac) * min_log

         return variance


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						torch.FloatTensor       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						torch.FloatTensor       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						List[str]=None       ,  __UpperCAmelCase     :						bool = True       ,  )						->				Union[UnCLIPSchedulerOutput, Tuple]:
         """simple docstring"""



         UpperCAmelCase__								=  timestep

         if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range":
               UpperCAmelCase__		,      UpperCAmelCase__								=  torch.split(__UpperCAmelCase       ,  sample.shape[1]       ,  dim=1		)
         else:
               UpperCAmelCase__								=  None

         # 1. compute alphas, betas
         if prev_timestep is None:
               UpperCAmelCase__								=  t - 1

         UpperCAmelCase__								=  self.alphas_cumprod[t]
         UpperCAmelCase__								=  self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one
         UpperCAmelCase__								=  1 - alpha_prod_t
         UpperCAmelCase__								=  1 - alpha_prod_t_prev

         if prev_timestep == t - 1:
               UpperCAmelCase__								=  self.betas[t]
               UpperCAmelCase__								=  self.alphas[t]
         else:
               UpperCAmelCase__								=  1 - alpha_prod_t / alpha_prod_t_prev
               UpperCAmelCase__								=  1 - beta

         # 2. compute predicted original sample from predicted noise also called
         # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
         if self.config.prediction_type == "epsilon":
               UpperCAmelCase__								=  (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
         elif self.config.prediction_type == "sample":
               UpperCAmelCase__								=  model_output
         else:
               raise ValueError(
                   f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`"""
                   " for the UnCLIPScheduler."		)

         # 3. Clip "predicted x_0"
         if self.config.clip_sample:
               UpperCAmelCase__								=  torch.clamp(
                   __UpperCAmelCase       ,  -self.config.clip_sample_range       ,  self.config.clip_sample_range		)

         # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
         # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
         UpperCAmelCase__								=  (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t
         UpperCAmelCase__								=  alpha ** 0.5 * beta_prod_t_prev / beta_prod_t

         # 5. Compute predicted previous sample µ_t
         # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
         UpperCAmelCase__								=  pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample

         # 6. Add noise
         UpperCAmelCase__								=  0
         if t > 0:
               UpperCAmelCase__								=  randn_tensor(
                   model_output.shape       ,  dtype=model_output.dtype       ,  generator=__UpperCAmelCase       ,  device=model_output.device		)

               UpperCAmelCase__								=  self._get_variance(
                   __UpperCAmelCase       ,  predicted_variance=__UpperCAmelCase       ,  prev_timestep=__UpperCAmelCase       ,  )

               if self.variance_type == "fixed_small_log":
                     UpperCAmelCase__								=  variance
               elif self.variance_type == "learned_range":
                     UpperCAmelCase__								=  (0.5 * variance).exp()
               else:
                     raise ValueError(
                         f"""variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`"""
                         " for the UnCLIPScheduler."		)

               UpperCAmelCase__								=  variance * variance_noise

         UpperCAmelCase__								=  pred_prev_sample + variance

         if not return_dict:
               return (pred_prev_sample,)

         return UnCLIPSchedulerOutput(prev_sample=__UpperCAmelCase       ,  pred_original_sample=__UpperCAmelCase		)





   def 			lowercase_      (self     :						Union[str, Any]       ,  __UpperCAmelCase     :						torch.FloatTensor       ,  __UpperCAmelCase     :						torch.FloatTensor       ,  __UpperCAmelCase     :						torch.IntTensor       ,  )						->				torch.FloatTensor:
         """simple docstring"""



         UpperCAmelCase__								=  self.alphas_cumprod.to(device=original_samples.device       ,  dtype=original_samples.dtype		)
         UpperCAmelCase__								=  timesteps.to(original_samples.device		)

         UpperCAmelCase__								=  alphas_cumprod[timesteps] ** 0.5
         UpperCAmelCase__								=  sqrt_alpha_prod.flatten()
         while len(sqrt_alpha_prod.shape		) < len(original_samples.shape		):
               UpperCAmelCase__								=  sqrt_alpha_prod.unsqueeze(-1		)

         UpperCAmelCase__								=  (1 - alphas_cumprod[timesteps]) ** 0.5
         UpperCAmelCase__								=  sqrt_one_minus_alpha_prod.flatten()
         while len(sqrt_one_minus_alpha_prod.shape		) < len(original_samples.shape		):
               UpperCAmelCase__								=  sqrt_one_minus_alpha_prod.unsqueeze(-1		)

         UpperCAmelCase__								=  sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
         return noisy_samples



