

"""simple docstring"""






import math
import os
import unittest

from transformers import MegatronBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, 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,
     MegatronBertForCausalLM,
     MegatronBertForMaskedLM,
     MegatronBertForMultipleChoice,
     MegatronBertForNextSentencePrediction,
     MegatronBertForPreTraining,
     MegatronBertForQuestionAnswering,
     MegatronBertForSequenceClassification,
     MegatronBertForTokenClassification,
     MegatronBertModel,
 )







class 	__UpperCamelCase    :

  def __init__(		self    ,_A    ,_A=13    ,_A=7    ,_A=True    ,_A=True    ,_A=True    ,_A=True    ,_A=99    ,_A=64    ,_A=32    ,_A=5    ,_A=4    ,_A=37    ,_A="gelu"    ,_A=0.1    ,_A=0.1    ,_A=512    ,_A=16    ,_A=2    ,_A=0.0_2    ,_A=3    ,_A=4    ,_A=None    ,):
      '''simple docstring'''

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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

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

      _lowerCAmelCase       :   Tuple  =    None
      if self.use_token_type_ids:
          _lowerCAmelCase       :   Any  =    ids_tensor([self.batch_size, self.seq_length]    ,self.type_vocab_size      )

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

      _lowerCAmelCase       :   str  =    self.get_config()

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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return MegatronBertConfig(
          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    ,embedding_size=self.embedding_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    ,is_decoder=_A    ,initializer_range=self.initializer_range    ,)

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    MegatronBertModel(config=_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   Any  =    model(_A    ,attention_mask=_A    ,token_type_ids=_A      )
      _lowerCAmelCase       :   Union[str, Any]  =    model(_A    ,token_type_ids=_A      )
      _lowerCAmelCase       :   Dict  =    model(_A      )

      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 __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    MegatronBertForMaskedLM(config=_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   List[Any]  =    model(_A    ,attention_mask=_A    ,token_type_ids=_A    ,labels=_A      )
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.seq_length, self.vocab_size)      )

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    MegatronBertForCausalLM(config=_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   Tuple  =    model(_A    ,attention_mask=_A    ,token_type_ids=_A    ,labels=_A      )
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.seq_length, self.vocab_size)      )

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    MegatronBertForNextSentencePrediction(config=_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   Union[str, Any]  =    model(
          _A    ,attention_mask=_A    ,token_type_ids=_A    ,labels=_A    ,)
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, 2)      )

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    MegatronBertForPreTraining(config=_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   Optional[int]  =    model(
          _A    ,attention_mask=_A    ,token_type_ids=_A    ,labels=_A    ,next_sentence_label=_A    ,)
      self.parent.assertEqual(result.prediction_logits.shape    ,(self.batch_size, self.seq_length, self.vocab_size)      )
      self.parent.assertEqual(result.seq_relationship_logits.shape    ,(self.batch_size, 2)      )

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    MegatronBertForQuestionAnswering(config=_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   Union[str, Any]  =    model(
          _A    ,attention_mask=_A    ,token_type_ids=_A    ,start_positions=_A    ,end_positions=_A    ,)
      self.parent.assertEqual(result.start_logits.shape    ,(self.batch_size, self.seq_length)      )
      self.parent.assertEqual(result.end_logits.shape    ,(self.batch_size, self.seq_length)      )

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    self.num_labels
      _lowerCAmelCase       :   Tuple  =    MegatronBertForSequenceClassification(_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   Any  =    model(_A    ,attention_mask=_A    ,token_type_ids=_A    ,labels=_A      )
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.num_labels)      )

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Dict  =    self.num_labels
      _lowerCAmelCase       :   str  =    MegatronBertForTokenClassification(config=_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   str  =    model(_A    ,attention_mask=_A    ,token_type_ids=_A    ,labels=_A      )
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.seq_length, self.num_labels)      )

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    self.num_choices
      _lowerCAmelCase       :   Dict  =    MegatronBertForMultipleChoice(config=_A      )
      model.to(_A      )
      model.eval()
      _lowerCAmelCase       :   Optional[int]  =    input_ids.unsqueeze(1      ).expand(-1    ,self.num_choices    ,-1      ).contiguous()
      _lowerCAmelCase       :   int  =    token_type_ids.unsqueeze(1      ).expand(-1    ,self.num_choices    ,-1      ).contiguous()
      _lowerCAmelCase       :   Optional[Any]  =    input_mask.unsqueeze(1      ).expand(-1    ,self.num_choices    ,-1      ).contiguous()
      _lowerCAmelCase       :   List[Any]  =    model(
          _A    ,attention_mask=_A    ,token_type_ids=_A    ,labels=_A    ,)
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.num_choices)      )







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    self.prepare_config_and_inputs()
      (
          (
          _lowerCAmelCase      
      ),					(
          _lowerCAmelCase      
      ),					(
          _lowerCAmelCase      
      ),					(
          _lowerCAmelCase      
      ),					(
          _lowerCAmelCase      
      ),					(
          _lowerCAmelCase      
      ),					(
          _lowerCAmelCase      
      ),					      
      )       :   List[Any]  =    config_and_inputs
      _lowerCAmelCase       :   List[Any]  =    {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
      return config, inputs_dict







@require_torch
class 	__UpperCamelCase    (    snake_case_							,							snake_case_							,							unittest.TestCase						):
  _UpperCAmelCase          =		(
      (
          MegatronBertModel,
          MegatronBertForMaskedLM,
          MegatronBertForCausalLM,
          MegatronBertForMultipleChoice,
          MegatronBertForNextSentencePrediction,
          MegatronBertForPreTraining,
          MegatronBertForQuestionAnswering,
          MegatronBertForSequenceClassification,
          MegatronBertForTokenClassification,
      )
      if is_torch_available()
      else ()
  )
  _UpperCAmelCase          =		(
      {
          """feature-extraction""": MegatronBertModel,
          """fill-mask""": MegatronBertForMaskedLM,
          """question-answering""": MegatronBertForQuestionAnswering,
          """text-classification""": MegatronBertForSequenceClassification,
          """text-generation""": MegatronBertForCausalLM,
          """token-classification""": MegatronBertForTokenClassification,
          """zero-shot""": MegatronBertForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  _UpperCAmelCase          =		True
  # test_resize_embeddings = False
  _UpperCAmelCase          =		False

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A=False      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    super()._prepare_for_class(_A    ,_A    ,return_labels=_A      )

      if return_labels:
          if model_class in get_values(_A      ):
              _lowerCAmelCase       :   Optional[Any]  =    torch.zeros(
                  (self.model_tester.batch_size, self.model_tester.seq_length)    ,dtype=torch.long    ,device=_A      )
              _lowerCAmelCase       :   Optional[Any]  =    torch.zeros(
                  self.model_tester.batch_size    ,dtype=torch.long    ,device=_A      )
      return inputs_dict

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    MegatronBertModelTester(self      )
      _lowerCAmelCase       :   List[Any]  =    ConfigTester(self    ,config_class=_A    ,hidden_size=37      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      self.config_tester.run_common_tests()

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_megatron_bert_model(*_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_megatron_bert_for_masked_lm(*_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_megatron_bert_for_pretraining(*_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_megatron_bert_for_question_answering(*_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*_A      )







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_megatron_bert_for_token_classification(*_A      )





def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



    return torch.tensor(
        _lowerCamelCase ,   dtype=torch.long ,   device=_lowerCamelCase ,   )


_lowerCAmelCase						=		1E-4







@require_torch
@require_sentencepiece
@require_tokenizers
class 	__UpperCamelCase    (    unittest.TestCase						):

  @slow
  @unittest.skip('Model is not available.'      )
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Dict  =    'nvidia/megatron-bert-uncased-345m'
      if "MYDIR" in os.environ:
          _lowerCAmelCase       :   List[str]  =    os.path.join(os.environ['MYDIR']    ,_A      )
      _lowerCAmelCase       :   Dict  =    MegatronBertModel.from_pretrained(_A      )
      model.to(_A      )
      model.half()
      _lowerCAmelCase       :   str  =    _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]]      )
      with torch.no_grad():
          _lowerCAmelCase       :   Optional[int]  =    model(_A      )[0]
      _lowerCAmelCase       :   List[Any]  =    torch.Size((1, 9, 1024)      )
      self.assertEqual(output.shape    ,_A      )

      _lowerCAmelCase       :   List[Any]  =    [-0.6_0_4_0, -0.2_5_1_7, -0.1_0_2_5, 0.3_4_2_0, -0.6_7_5_8, -0.0_0_1_7, -0.1_0_8_9, -0.1_9_9_0, 0.5_7_2_8]
      for ii in range(3      ):
          for jj in range(3      ):
              _lowerCAmelCase       :   int  =    output[0, ii, jj]
              _lowerCAmelCase       :   Optional[Any]  =    expected[3 * ii + jj]
              _lowerCAmelCase       :   Dict  =    'ii={} jj={} a={} b={}'.format(_A    ,_A    ,_A    ,_A      )
              self.assertTrue(math.isclose(_A    ,_A    ,rel_tol=_A    ,abs_tol=_A      )    ,msg=_A      )







"""simple docstring"""






from math import acos, sin
from typing import List, Tuple, Union

import numpy as np
import torch
from PIL import Image

from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel







class 	__UpperCamelCase    (    a__						):
  _UpperCAmelCase          =		["vqvae"]

  def __init__(		self    ,_A    ,_A    ,_A    ,_A    ,):
      '''simple docstring'''

      super().__init__()
      self.register_modules(unet=_A    ,scheduler=_A    ,mel=_A    ,vqvae=_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return 50 if isinstance(self.scheduler    ,_A      ) else 1000

  @torch.no_grad()
  def __call__(		self    ,_A = 1    ,_A = None    ,_A = None    ,_A = 0    ,_A = 0    ,_A = None    ,_A = None    ,_A = 0    ,_A = 0    ,_A = None    ,_A = 0    ,_A = None    ,_A = None    ,_A=True    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    steps or self.get_default_steps()
      self.scheduler.set_timesteps(_A      )
      _lowerCAmelCase       :   Optional[Any]  =    step_generator or generator
      # For backwards compatibility
      if type(self.unet.config.sample_size      ) == int:
          _lowerCAmelCase       :   Tuple  =    (self.unet.config.sample_size, self.unet.config.sample_size)
      if noise is None:
          _lowerCAmelCase       :   Optional[Any]  =    randn_tensor(
              (
                  batch_size,
                  self.unet.config.in_channels,
                  self.unet.config.sample_size[0],
                  self.unet.config.sample_size[1],
              )    ,generator=_A    ,device=self.device    ,)
      _lowerCAmelCase       :   Dict  =    noise
      _lowerCAmelCase       :   Optional[Any]  =    None

      if audio_file is not None or raw_audio is not None:
          self.mel.load_audio(_A    ,_A      )
          _lowerCAmelCase       :   Union[str, Any]  =    self.mel.audio_slice_to_image(_A      )
          _lowerCAmelCase       :   int  =    np.frombuffer(input_image.tobytes()    ,dtype='uint8'      ).reshape(
              (input_image.height, input_image.width)      )
          _lowerCAmelCase       :   int  =    (input_image / 255) * 2 - 1
          _lowerCAmelCase       :   str  =    torch.tensor(input_image[np.newaxis, :, :]    ,dtype=torch.float      ).to(self.device      )

          if self.vqvae is not None:
              _lowerCAmelCase       :   List[Any]  =    self.vqvae.encode(torch.unsqueeze(_A    ,0      )      ).latent_dist.sample(
                  generator=_A      )[0]
              _lowerCAmelCase       :   Tuple  =    self.vqvae.config.scaling_factor * input_images

          if start_step > 0:
              _lowerCAmelCase       :   List[Any]  =    self.scheduler.add_noise(_A    ,_A    ,self.scheduler.timesteps[start_step - 1]      )

          _lowerCAmelCase       :   Optional[Any]  =    (
              self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
          )
          _lowerCAmelCase       :   Optional[Any]  =    int(mask_start_secs * pixels_per_second      )
          _lowerCAmelCase       :   Optional[int]  =    int(mask_end_secs * pixels_per_second      )
          _lowerCAmelCase       :   int  =    self.scheduler.add_noise(_A    ,_A    ,torch.tensor(self.scheduler.timesteps[start_step:]      )      )

      for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]      )      ):
          if isinstance(self.unet    ,_A      ):
              _lowerCAmelCase       :   str  =    self.unet(_A    ,_A    ,_A      )['sample']
          else:
              _lowerCAmelCase       :   Any  =    self.unet(_A    ,_A      )['sample']

          if isinstance(self.scheduler    ,_A      ):
              _lowerCAmelCase       :   Union[str, Any]  =    self.scheduler.step(
                  model_output=_A    ,timestep=_A    ,sample=_A    ,eta=_A    ,generator=_A    ,)['prev_sample']
          else:
              _lowerCAmelCase       :   Any  =    self.scheduler.step(
                  model_output=_A    ,timestep=_A    ,sample=_A    ,generator=_A    ,)['prev_sample']

          if mask is not None:
              if mask_start > 0:
                  _lowerCAmelCase       :   Any  =    mask[:, step, :, :mask_start]
              if mask_end > 0:
                  _lowerCAmelCase       :   Optional[Any]  =    mask[:, step, :, -mask_end:]

      if self.vqvae is not None:
          # 0.18215 was scaling factor used in training to ensure unit variance
          _lowerCAmelCase       :   Union[str, Any]  =    1 / self.vqvae.config.scaling_factor * images
          _lowerCAmelCase       :   Any  =    self.vqvae.decode(_A      )['sample']

      _lowerCAmelCase       :   Any  =    (images / 2 + 0.5).clamp(0    ,1      )
      _lowerCAmelCase       :   Tuple  =    images.cpu().permute(0    ,2    ,3    ,1      ).numpy()
      _lowerCAmelCase       :   Any  =    (images * 255).round().astype('uint8'      )
      _lowerCAmelCase       :   Any  =    list(
          (Image.fromarray(_[:, :, 0]      ) for _ in images)
          if images.shape[3] == 1
          else (Image.fromarray(_A    ,mode='RGB'      ).convert('L'      ) for _ in images)      )

      _lowerCAmelCase       :   Dict  =    [self.mel.image_to_audio(_A      ) for _ in images]
      if not return_dict:
          return images, (self.mel.get_sample_rate(), audios)

      return BaseOutput(**AudioPipelineOutput(np.array(_A      )[:, np.newaxis, :]      )    ,**ImagePipelineOutput(_A      )      )

  @torch.no_grad()
  def __lowerCamelCase		(		self    ,_A    ,_A = 50      ):
      '''simple docstring'''

      assert isinstance(self.scheduler    ,_A      )
      self.scheduler.set_timesteps(_A      )
      _lowerCAmelCase       :   Dict  =    np.array(
          [np.frombuffer(image.tobytes()    ,dtype='uint8'      ).reshape((1, image.height, image.width)      ) for image in images]      )
      _lowerCAmelCase       :   Dict  =    (sample / 255) * 2 - 1
      _lowerCAmelCase       :   List[str]  =    torch.Tensor(_A      ).to(self.device      )

      for t in self.progress_bar(torch.flip(self.scheduler.timesteps    ,(0,)      )      ):
          _lowerCAmelCase       :   Tuple  =    t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
          _lowerCAmelCase       :   Optional[int]  =    self.scheduler.alphas_cumprod[t]
          _lowerCAmelCase       :   Dict  =    (
              self.scheduler.alphas_cumprod[prev_timestep]
              if prev_timestep >= 0
              else self.scheduler.final_alpha_cumprod
          )
          _lowerCAmelCase       :   Union[str, Any]  =    1 - alpha_prod_t
          _lowerCAmelCase       :   Union[str, Any]  =    self.unet(_A    ,_A      )['sample']
          _lowerCAmelCase       :   Optional[int]  =    (1 - alpha_prod_t_prev) ** 0.5 * model_output
          _lowerCAmelCase       :   Any  =    (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
          _lowerCAmelCase       :   Dict  =    sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

      return sample







  @staticmethod
  def __lowerCamelCase		(		_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    acos(torch.dot(torch.flatten(_A      )    ,torch.flatten(_A      )      ) / torch.norm(_A      ) / torch.norm(_A      )      )
      return sin((1 - alpha) * theta      ) * xa / sin(_A      ) + sin(alpha * theta      ) * xa / sin(_A      )





