





import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput

def     a_       (					lowerCAmelCase_ :     Optional[int],      lowerCAmelCase_ :     List[Any]=0.999,      lowerCAmelCase_ :     List[str]="cosine",      ):
   if alpha_transform_type == "cosine":

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

   elif alpha_transform_type == "exp":

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

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

   __lowerCAmelCase				      =      []
   for i in range(lowerCAmelCase_      ):
      __lowerCAmelCase				      =      i / num_diffusion_timesteps
      __lowerCAmelCase				      =      (i + 1) / num_diffusion_timesteps
      betas.append(min(1 - alpha_bar_fn(lowerCAmelCase_      ) / alpha_bar_fn(lowerCAmelCase_      ),      lowerCAmelCase_      )      )
   return torch.tensor(lowerCAmelCase_,      dtype=torch.floataa      )




class 							_UpperCAmelCase       (       _UpperCamelCase						,       _UpperCamelCase       ):

  """simple docstring"""


  a_              =					[e.name for e in KarrasDiffusionSchedulers]
  a_              =					2






  @register_to_config
  def __init__(							self					:						int   ,    lowerCAmelCase_					:						int = 1_0_0_0   ,    lowerCAmelCase_					:						float = 0.0_00_85   ,    lowerCAmelCase_					:						float = 0.0_12   ,    lowerCAmelCase_					:						str = "linear"   ,    lowerCAmelCase_					:						Optional[Union[np.ndarray, List[float]]] = None   ,    lowerCAmelCase_					:						str = "epsilon"   ,    lowerCAmelCase_					:						Optional[bool] = False   ,    lowerCAmelCase_					:						Optional[bool] = False   ,    lowerCAmelCase_					:						float = 1.0   ,    lowerCAmelCase_					:						str = "linspace"   ,    lowerCAmelCase_					:						int = 0   ,    )				->		List[Any]:
     if trained_betas is not None:
        __lowerCAmelCase				      =      torch.tensor(lowerCAmelCase_   ,    dtype=torch.floataa	)
     elif beta_schedule == "linear":
        __lowerCAmelCase				      =      torch.linspace(lowerCAmelCase_   ,    lowerCAmelCase_   ,    lowerCAmelCase_   ,    dtype=torch.floataa	)
     elif beta_schedule == "scaled_linear":
        # this schedule is very specific to the latent diffusion model.
        __lowerCAmelCase				      =      (
            torch.linspace(beta_start**0.5   ,    beta_end**0.5   ,    lowerCAmelCase_   ,    dtype=torch.floataa	) ** 2
        )
     elif beta_schedule == "squaredcos_cap_v2":
        # Glide cosine schedule
        __lowerCAmelCase				      =      betas_for_alpha_bar(lowerCAmelCase_   ,    alpha_transform_type='cosine'	)
     elif beta_schedule == "exp":
        __lowerCAmelCase				      =      betas_for_alpha_bar(lowerCAmelCase_   ,    alpha_transform_type='exp'	)
     else:
        raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}"""	)

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

     #  set all values
     self.set_timesteps(lowerCAmelCase_   ,    lowerCAmelCase_   ,    lowerCAmelCase_	)
     __lowerCAmelCase				      =      use_karras_sigmas






  def 							lowercase						(							self					:						Optional[int]   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						Optional[Any]=None	)				->		str:
     if schedule_timesteps is None:
        __lowerCAmelCase				      =      self.timesteps

     __lowerCAmelCase				      =      (schedule_timesteps == timestep).nonzero()

     # The sigma index that is taken for the **very** first `step`
     # is always the second index (or the last index if there is only 1)
     # This way we can ensure we don't accidentally skip a sigma in
     # case we start in the middle of the denoising schedule (e.g. for image-to-image)
     if len(self._index_counter	) == 0:
        __lowerCAmelCase				      =      1 if len(lowerCAmelCase_	) > 1 else 0
     else:
        __lowerCAmelCase				      =      timestep.cpu().item() if torch.is_tensor(lowerCAmelCase_	) else timestep
        __lowerCAmelCase				      =      self._index_counter[timestep_int]

     return indices[pos].item()






  @property
  def 							lowercase						(							self					:						Any	)				->		List[Any]:
     # standard deviation of the initial noise distribution
     if self.config.timestep_spacing in ["linspace", "trailing"]:
        return self.sigmas.max()

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






  def 							lowercase						(							self					:						Optional[Any]   ,    lowerCAmelCase_					:						torch.FloatTensor   ,    lowerCAmelCase_					:						Union[float, torch.FloatTensor]   ,    )				->		torch.FloatTensor:
     __lowerCAmelCase				      =      self.index_for_timestep(lowerCAmelCase_	)

     __lowerCAmelCase				      =      self.sigmas[step_index]
     __lowerCAmelCase				      =      sample / ((sigma**2 + 1) ** 0.5)
     return sample






  def 							lowercase						(							self					:						List[Any]   ,    lowerCAmelCase_					:						int   ,    lowerCAmelCase_					:						Union[str, torch.device] = None   ,    lowerCAmelCase_					:						Optional[int] = None   ,    )				->		Union[str, Any]:
     __lowerCAmelCase				      =      num_inference_steps

     __lowerCAmelCase				      =      num_train_timesteps or self.config.num_train_timesteps

     # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
     if self.config.timestep_spacing == "linspace":
        __lowerCAmelCase				      =      np.linspace(0   ,    num_train_timesteps - 1   ,    lowerCAmelCase_   ,    dtype=lowerCAmelCase_	)[::-1].copy()
     elif self.config.timestep_spacing == "leading":
        __lowerCAmelCase				      =      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
        __lowerCAmelCase				      =      (np.arange(0   ,    lowerCAmelCase_	) * step_ratio).round()[::-1].copy().astype(lowerCAmelCase_	)
        timesteps += self.config.steps_offset
     elif self.config.timestep_spacing == "trailing":
        __lowerCAmelCase				      =      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
        __lowerCAmelCase				      =      (np.arange(lowerCAmelCase_   ,    0   ,    -step_ratio	)).round().copy().astype(lowerCAmelCase_	)
        timesteps -= 1
     else:
        raise ValueError(
            f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."""	)

     __lowerCAmelCase				      =      np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5	)
     __lowerCAmelCase				      =      np.log(lowerCAmelCase_	)
     __lowerCAmelCase				      =      np.interp(lowerCAmelCase_   ,    np.arange(0   ,    len(lowerCAmelCase_	)	)   ,    lowerCAmelCase_	)

     if self.config.use_karras_sigmas:
        __lowerCAmelCase				      =      self._convert_to_karras(in_sigmas=lowerCAmelCase_   ,    num_inference_steps=self.num_inference_steps	)
        __lowerCAmelCase				      =      np.array([self._sigma_to_t(lowerCAmelCase_   ,    lowerCAmelCase_	) for sigma in sigmas]	)

     __lowerCAmelCase				      =      np.concatenate([sigmas, [0.0]]	).astype(np.floataa	)
     __lowerCAmelCase				      =      torch.from_numpy(lowerCAmelCase_	).to(device=lowerCAmelCase_	)
     __lowerCAmelCase				      =      torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2	), sigmas[-1:]]	)

     __lowerCAmelCase				      =      torch.from_numpy(lowerCAmelCase_	)
     __lowerCAmelCase				      =      torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2	)]	)

     if str(lowerCAmelCase_	).startswith('mps'	):
        # mps does not support float64
        __lowerCAmelCase				      =      timesteps.to(lowerCAmelCase_   ,    dtype=torch.floataa	)
     else:
        __lowerCAmelCase				      =      timesteps.to(device=lowerCAmelCase_	)

     # empty dt and derivative
     __lowerCAmelCase				      =      None
     __lowerCAmelCase				      =      None

     # for exp beta schedules, such as the one for `pipeline_shap_e.py`
     # we need an index counter
     __lowerCAmelCase				      =      defaultdict(lowerCAmelCase_	)






  def 							lowercase						(							self					:						Tuple   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						List[Any]	)				->		int:
     # get log sigma
     __lowerCAmelCase				      =      np.log(lowerCAmelCase_	)

     # get distribution
     __lowerCAmelCase				      =      log_sigma - log_sigmas[:, np.newaxis]

     # get sigmas range
     __lowerCAmelCase				      =      np.cumsum((dists >= 0)   ,    axis=0	).argmax(axis=0	).clip(max=log_sigmas.shape[0] - 2	)
     __lowerCAmelCase				      =      low_idx + 1

     __lowerCAmelCase				      =      log_sigmas[low_idx]
     __lowerCAmelCase				      =      log_sigmas[high_idx]

     # interpolate sigmas
     __lowerCAmelCase				      =      (low - log_sigma) / (low - high)
     __lowerCAmelCase				      =      np.clip(lowerCAmelCase_   ,    0   ,    1	)

     # transform interpolation to time range
     __lowerCAmelCase				      =      (1 - w) * low_idx + w * high_idx
     __lowerCAmelCase				      =      t.reshape(sigma.shape	)
     return t






  def 							lowercase						(							self					:						Tuple   ,    lowerCAmelCase_					:						torch.FloatTensor   ,    lowerCAmelCase_					:						Optional[Any]	)				->		torch.FloatTensor:
     __lowerCAmelCase				      =      in_sigmas[-1].item()
     __lowerCAmelCase				      =      in_sigmas[0].item()

     __lowerCAmelCase				      =      7.0  # 7.0 is the value used in the paper
     __lowerCAmelCase				      =      np.linspace(0   ,    1   ,    lowerCAmelCase_	)
     __lowerCAmelCase				      =      sigma_min ** (1 / rho)
     __lowerCAmelCase				      =      sigma_max ** (1 / rho)
     __lowerCAmelCase				      =      (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
     return sigmas






  @property
  def 							lowercase						(							self					:						List[str]	)				->		Any:
     return self.dt is None






  def 							lowercase						(							self					:						Union[str, Any]   ,    lowerCAmelCase_					:						Union[torch.FloatTensor, np.ndarray]   ,    lowerCAmelCase_					:						Union[float, torch.FloatTensor]   ,    lowerCAmelCase_					:						Union[torch.FloatTensor, np.ndarray]   ,    lowerCAmelCase_					:						bool = True   ,    )				->		Union[SchedulerOutput, Tuple]:
     __lowerCAmelCase				      =      self.index_for_timestep(lowerCAmelCase_	)

     # advance index counter by 1
     __lowerCAmelCase				      =      timestep.cpu().item() if torch.is_tensor(lowerCAmelCase_	) else timestep
     self._index_counter[timestep_int] += 1

     if self.state_in_first_order:
        __lowerCAmelCase				      =      self.sigmas[step_index]
        __lowerCAmelCase				      =      self.sigmas[step_index + 1]
     else:
        # 2nd order / Heun's method
        __lowerCAmelCase				      =      self.sigmas[step_index - 1]
        __lowerCAmelCase				      =      self.sigmas[step_index]

     # currently only gamma=0 is supported. This usually works best anyways.
     # We can support gamma in the future but then need to scale the timestep before
     # passing it to the model which requires a change in API
     __lowerCAmelCase				      =      0
     __lowerCAmelCase				      =      sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

     # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
     if self.config.prediction_type == "epsilon":
        __lowerCAmelCase				      =      sigma_hat if self.state_in_first_order else sigma_next
        __lowerCAmelCase				      =      sample - sigma_input * model_output
     elif self.config.prediction_type == "v_prediction":
        __lowerCAmelCase				      =      sigma_hat if self.state_in_first_order else sigma_next
        __lowerCAmelCase				      =      model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
            sample / (sigma_input**2 + 1)
        )
     elif self.config.prediction_type == "sample":
        __lowerCAmelCase				      =      model_output
     else:
        raise ValueError(
            f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"""	)

     if self.config.clip_sample:
        __lowerCAmelCase				      =      pred_original_sample.clamp(
            -self.config.clip_sample_range   ,    self.config.clip_sample_range	)

     if self.state_in_first_order:
        # 2. Convert to an ODE derivative for 1st order
        __lowerCAmelCase				      =      (sample - pred_original_sample) / sigma_hat
        # 3. delta timestep
        __lowerCAmelCase				      =      sigma_next - sigma_hat

        # store for 2nd order step
        __lowerCAmelCase				      =      derivative
        __lowerCAmelCase				      =      dt
        __lowerCAmelCase				      =      sample
     else:
        # 2. 2nd order / Heun's method
        __lowerCAmelCase				      =      (sample - pred_original_sample) / sigma_next
        __lowerCAmelCase				      =      (self.prev_derivative + derivative) / 2

        # 3. take prev timestep & sample
        __lowerCAmelCase				      =      self.dt
        __lowerCAmelCase				      =      self.sample

        # free dt and derivative
        # Note, this puts the scheduler in "first order mode"
        __lowerCAmelCase				      =      None
        __lowerCAmelCase				      =      None
        __lowerCAmelCase				      =      None

     __lowerCAmelCase				      =      sample + derivative * dt

     if not return_dict:
        return (prev_sample,)

     return SchedulerOutput(prev_sample=lowerCAmelCase_	)






  def 							lowercase						(							self					:						List[Any]   ,    lowerCAmelCase_					:						torch.FloatTensor   ,    lowerCAmelCase_					:						torch.FloatTensor   ,    lowerCAmelCase_					:						torch.FloatTensor   ,    )				->		torch.FloatTensor:
     # Make sure sigmas and timesteps have the same device and dtype as original_samples
     __lowerCAmelCase				      =      self.sigmas.to(device=original_samples.device   ,    dtype=original_samples.dtype	)
     if original_samples.device.type == "mps" and torch.is_floating_point(lowerCAmelCase_	):
        # mps does not support float64
        __lowerCAmelCase				      =      self.timesteps.to(original_samples.device   ,    dtype=torch.floataa	)
        __lowerCAmelCase				      =      timesteps.to(original_samples.device   ,    dtype=torch.floataa	)
     else:
        __lowerCAmelCase				      =      self.timesteps.to(original_samples.device	)
        __lowerCAmelCase				      =      timesteps.to(original_samples.device	)

     __lowerCAmelCase				      =      [self.index_for_timestep(lowerCAmelCase_   ,    lowerCAmelCase_	) for t in timesteps]

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

     __lowerCAmelCase				      =      original_samples + noise * sigma
     return noisy_samples






  def __len__(							self					:						Union[str, Any]	)				->		Union[str, Any]:
     return self.config.num_train_timesteps






import unittest

from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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 (
	    MODEL_FOR_PRETRAINING_MAPPING,
	    AlbertForMaskedLM,
	    AlbertForMultipleChoice,
	    AlbertForPreTraining,
	    AlbertForQuestionAnswering,
	    AlbertForSequenceClassification,
	    AlbertForTokenClassification,
	    AlbertModel,
	)
	from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST







class 				_a				:

			def __init__(self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_=13,   SCREAMING_SNAKE_CASE_=7,   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=99,   SCREAMING_SNAKE_CASE_=16,   SCREAMING_SNAKE_CASE_=36,   SCREAMING_SNAKE_CASE_=6,   SCREAMING_SNAKE_CASE_=6,   SCREAMING_SNAKE_CASE_=6,   SCREAMING_SNAKE_CASE_=37,   SCREAMING_SNAKE_CASE_="gelu",   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_=512,   SCREAMING_SNAKE_CASE_=16,   SCREAMING_SNAKE_CASE_=2,   SCREAMING_SNAKE_CASE_=0.0_2,   SCREAMING_SNAKE_CASE_=3,   SCREAMING_SNAKE_CASE_=4,   SCREAMING_SNAKE_CASE_=None,   )       ->   Tuple:
						UpperCAmelCase_:		Any							      =     parent
						UpperCAmelCase_:		Union[str, Any]							      =     batch_size
						UpperCAmelCase_:		int							      =     seq_length
						UpperCAmelCase_:		Any							      =     is_training
						UpperCAmelCase_:		str							      =     use_input_mask
						UpperCAmelCase_:		Dict							      =     use_token_type_ids
						UpperCAmelCase_:		Any							      =     use_labels
						UpperCAmelCase_:		Any							      =     vocab_size
						UpperCAmelCase_:		Dict							      =     embedding_size
						UpperCAmelCase_:		Dict							      =     hidden_size
						UpperCAmelCase_:		Dict							      =     num_hidden_layers
						UpperCAmelCase_:		Dict							      =     num_hidden_groups
						UpperCAmelCase_:		int							      =     num_attention_heads
						UpperCAmelCase_:		List[str]							      =     intermediate_size
						UpperCAmelCase_:		Any							      =     hidden_act
						UpperCAmelCase_:		Dict							      =     hidden_dropout_prob
						UpperCAmelCase_:		Any							      =     attention_probs_dropout_prob
						UpperCAmelCase_:		Tuple							      =     max_position_embeddings
						UpperCAmelCase_:		Tuple							      =     type_vocab_size
						UpperCAmelCase_:		List[Any]							      =     type_sequence_label_size
						UpperCAmelCase_:		Any							      =     initializer_range
						UpperCAmelCase_:		int							      =     num_labels
						UpperCAmelCase_:		Optional[int]							      =     num_choices
						UpperCAmelCase_:		Tuple							      =     scope

			def      __snake_case       (self					)       ->   List[Any]:
						UpperCAmelCase_:		Union[str, Any]							      =     ids_tensor([self.batch_size, self.seq_length],   self.vocab_size					)

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

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

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

						UpperCAmelCase_:		Optional[int]							      =     self.get_config()

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

			def      __snake_case       (self					)       ->   Optional[Any]:
						return AlbertConfig(
						    vocab_size=self.vocab_size,   hidden_size=self.hidden_size,   num_hidden_layers=self.num_hidden_layers,   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,   num_hidden_groups=self.num_hidden_groups,   )

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Optional[Any]:
						UpperCAmelCase_:		int							      =     AlbertModel(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		Optional[int]							      =     model(SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		List[Any]							      =     model(SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Union[str, Any]							      =     model(SCREAMING_SNAKE_CASE_					)
						self.parent.assertEqual(result.last_hidden_state.shape,   (self.batch_size, self.seq_length, self.hidden_size)					)
						self.parent.assertEqual(result.pooler_output.shape,   (self.batch_size, self.hidden_size)					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   str:
						UpperCAmelCase_:		Any							      =     AlbertForPreTraining(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		List[Any]							      =     model(
						    SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   labels=SCREAMING_SNAKE_CASE_,   sentence_order_label=SCREAMING_SNAKE_CASE_,   )
						self.parent.assertEqual(result.prediction_logits.shape,   (self.batch_size, self.seq_length, self.vocab_size)					)
						self.parent.assertEqual(result.sop_logits.shape,   (self.batch_size, config.num_labels)					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   List[str]:
						UpperCAmelCase_:		Optional[int]							      =     AlbertForMaskedLM(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		Optional[Any]							      =     model(SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   labels=SCREAMING_SNAKE_CASE_					)
						self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.seq_length, self.vocab_size)					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Tuple:
						UpperCAmelCase_:		Optional[Any]							      =     AlbertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		Any							      =     model(
						    SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   start_positions=SCREAMING_SNAKE_CASE_,   end_positions=SCREAMING_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      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Any:
						UpperCAmelCase_:		Optional[Any]							      =     self.num_labels
						UpperCAmelCase_:		List[Any]							      =     AlbertForSequenceClassification(SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		str							      =     model(SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   labels=SCREAMING_SNAKE_CASE_					)
						self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_labels)					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   List[Any]:
						UpperCAmelCase_:		List[str]							      =     self.num_labels
						UpperCAmelCase_:		Union[str, Any]							      =     AlbertForTokenClassification(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		List[str]							      =     model(SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   labels=SCREAMING_SNAKE_CASE_					)
						self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.seq_length, self.num_labels)					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Dict:
						UpperCAmelCase_:		Dict							      =     self.num_choices
						UpperCAmelCase_:		Dict							      =     AlbertForMultipleChoice(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		str							      =     input_ids.unsqueeze(1					).expand(-1,   self.num_choices,   -1					).contiguous()
						UpperCAmelCase_:		str							      =     token_type_ids.unsqueeze(1					).expand(-1,   self.num_choices,   -1					).contiguous()
						UpperCAmelCase_:		List[Any]							      =     input_mask.unsqueeze(1					).expand(-1,   self.num_choices,   -1					).contiguous()
						UpperCAmelCase_:		Union[str, Any]							      =     model(
						    SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_,   token_type_ids=SCREAMING_SNAKE_CASE_,   labels=SCREAMING_SNAKE_CASE_,   )
						self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_choices)					)

			def      __snake_case       (self					)       ->   Union[str, Any]:
						UpperCAmelCase_:		Optional[Any]							      =     self.prepare_config_and_inputs()
						(
						    (
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							
						):		List[str]							      =     config_and_inputs
						UpperCAmelCase_:		Tuple							      =     {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
						return config, inputs_dict







@require_torch
class 				_a				(   _lowerCAmelCase ,		_lowerCAmelCase ,		unittest.TestCase					):
			A      		=	(
			    (
			        AlbertModel,
			        AlbertForPreTraining,
			        AlbertForMaskedLM,
			        AlbertForMultipleChoice,
			        AlbertForSequenceClassification,
			        AlbertForTokenClassification,
			        AlbertForQuestionAnswering,
			    )
			    if is_torch_available()
			    else ()
			)
			A      		=	(
			    {
			        '''feature-extraction''': AlbertModel,
			        '''fill-mask''': AlbertForMaskedLM,
			        '''question-answering''': AlbertForQuestionAnswering,
			        '''text-classification''': AlbertForSequenceClassification,
			        '''token-classification''': AlbertForTokenClassification,
			        '''zero-shot''': AlbertForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			A      		=	True

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_=False					)       ->   Any:
						UpperCAmelCase_:		Tuple							      =     super()._prepare_for_class(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   return_labels=SCREAMING_SNAKE_CASE_					)

						if return_labels:
									if model_class in get_values(SCREAMING_SNAKE_CASE_					):
												UpperCAmelCase_:		Dict							      =     torch.zeros(
												    (self.model_tester.batch_size, self.model_tester.seq_length),   dtype=torch.long,   device=SCREAMING_SNAKE_CASE_					)
												UpperCAmelCase_:		Optional[int]							      =     torch.zeros(
												    self.model_tester.batch_size,   dtype=torch.long,   device=SCREAMING_SNAKE_CASE_					)
						return inputs_dict

			def      __snake_case       (self					)       ->   Optional[Any]:
						UpperCAmelCase_:		Any							      =     AlbertModelTester(self					)
						UpperCAmelCase_:		Union[str, Any]							      =     ConfigTester(self,   config_class=SCREAMING_SNAKE_CASE_,   hidden_size=37					)

			def      __snake_case       (self					)       ->   List[Any]:
						self.config_tester.run_common_tests()

			def      __snake_case       (self					)       ->   List[Any]:
						UpperCAmelCase_:		List[Any]							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   Any:
						UpperCAmelCase_:		int							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_pretraining(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   Optional[Any]:
						UpperCAmelCase_:		Tuple							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   str:
						UpperCAmelCase_:		Optional[Any]							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   Any:
						UpperCAmelCase_:		List[str]							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   str:
						UpperCAmelCase_:		Optional[int]							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   Dict:
						UpperCAmelCase_:		Optional[Any]							      =     self.model_tester.prepare_config_and_inputs()
						for type in ["absolute", "relative_key", "relative_key_query"]:
									UpperCAmelCase_:		Union[str, Any]							      =     type
									self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_					)

			@slow
			def      __snake_case       (self					)       ->   List[Any]:
						for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									UpperCAmelCase_:		Dict							      =     AlbertModel.from_pretrained(SCREAMING_SNAKE_CASE_					)
									self.assertIsNotNone(SCREAMING_SNAKE_CASE_					)







@require_torch
class 				_a				(   unittest.TestCase					):

			@slow
			def      __snake_case       (self					)       ->   Dict:
						UpperCAmelCase_:		str							      =     AlbertModel.from_pretrained("""albert-base-v2"""					)
						UpperCAmelCase_:		List[str]							      =     torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]					)
						UpperCAmelCase_:		List[str]							      =     torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]					)
						with torch.no_grad():
									UpperCAmelCase_:		Union[str, Any]							      =     model(SCREAMING_SNAKE_CASE_,   attention_mask=SCREAMING_SNAKE_CASE_					)[0]
						UpperCAmelCase_:		List[str]							      =     torch.Size((1, 11, 768)					)
						self.assertEqual(output.shape,   SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Dict							      =     torch.tensor(
						    [[[-0.6_5_1_3, 1.5_0_3_5, -0.2_7_6_6], [-0.6_5_1_5, 1.5_0_4_6, -0.2_7_8_0], [-0.6_5_1_2, 1.5_0_4_9, -0.2_7_8_4]]]					)

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






