

from typing import List, Optional, Tuple, Union

import torch

from ...models import UNetaDModel
from ...schedulers import PNDMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput



class 					lowercase		( _UpperCamelCase      ):



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE      							=       42
 __SCREAMING_SNAKE_CASE      							=       42




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






  """simple docstring"""





  super().__init__()

  UpperCAmelCase__           =       PNDMScheduler.from_config(scheduler.config				)

  self.register_modules(unet=__a , scheduler=__a				)




 @torch.no_grad()
 def __call__(self , __a = 1 , __a = 50 , __a = None , __a = "pil" , __a = True , **__a , )				->      Union[ImagePipelineOutput, Tuple]:






  """simple docstring"""





  UpperCAmelCase__           =       randn_tensor(
      (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=__a , device=self.device , )

  self.scheduler.set_timesteps(__a				)
  for t in self.progress_bar(self.scheduler.timesteps				):
   UpperCAmelCase__           =       self.unet(__a , __a				).sample

   UpperCAmelCase__           =       self.scheduler.step(__a , __a , __a				).prev_sample

  UpperCAmelCase__           =       (image / 2 + 0.5).clamp(0 , 1				)
  UpperCAmelCase__           =       image.cpu().permute(0 , 2 , 3 , 1				).numpy()
  if output_type == "pil":
   UpperCAmelCase__           =       self.numpy_to_pil(__a				)

  if not return_dict:
   return (image,)

  return ImagePipelineOutput(images=__a				)






import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VivitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor


if is_torch_available():
 import torch
 from torch import nn

 from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VivitForVideoClassification, VivitModel
 from transformers.models.vivit.modeling_vivit import VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from transformers import VivitImageProcessor



class 					lowercase		:



 '''simple docstring'''


 def __init__(self , __a , __a=2 , __a=True , __a=True , __a=10 , __a=10 , __a=8 , __a=[2, 4, 4] , __a=3 , __a=768 , __a=5 , __a=4 , __a=37 , __a="gelu_fast" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-0_6 , __a=True , __a=None , )				->      List[Any]:






  """simple docstring"""





  UpperCAmelCase__           =       parent
  UpperCAmelCase__           =       batch_size
  UpperCAmelCase__           =       is_training
  UpperCAmelCase__           =       use_labels
  UpperCAmelCase__           =       num_labels
  UpperCAmelCase__           =       image_size
  UpperCAmelCase__           =       num_frames
  UpperCAmelCase__           =       tubelet_size
  UpperCAmelCase__           =       num_channels
  UpperCAmelCase__           =       hidden_size
  UpperCAmelCase__           =       num_hidden_layers
  UpperCAmelCase__           =       num_attention_heads
  UpperCAmelCase__           =       intermediate_size
  UpperCAmelCase__           =       hidden_act
  UpperCAmelCase__           =       hidden_dropout_prob
  UpperCAmelCase__           =       attention_probs_dropout_prob
  UpperCAmelCase__           =       initializer_range
  UpperCAmelCase__           =       layer_norm_eps
  UpperCAmelCase__           =       qkv_bias
  UpperCAmelCase__           =       scope

  UpperCAmelCase__           =       (
      (self.image_size // self.tubelet_size[2])
      * (self.image_size // self.tubelet_size[1])
      * (self.num_frames // self.tubelet_size[0])
  ) + 1  # CLS token




 def 						UpperCamelCase__							(self				)				->      Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__           =       floats_tensor(
      [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]				)

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

  UpperCAmelCase__           =       self.get_config()

  return config, pixel_values, labels




 def 						UpperCamelCase__							(self				)				->      Tuple:






  """simple docstring"""





  UpperCAmelCase__           =       VivitConfig(
      num_frames=self.num_frames , image_size=self.image_size , tubelet_size=self.tubelet_size , num_channels=self.num_channels , 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 , initializer_range=self.initializer_range , layer_norm_eps=self.layer_norm_eps , qkv_bias=self.qkv_bias , )
  UpperCAmelCase__           =       self.num_labels
  return config




 def 						UpperCamelCase__							(self , __a , __a , __a				)				->      str:






  """simple docstring"""





  UpperCAmelCase__           =       VivitModel(config=__a				)
  model.to(__a				)
  model.eval()
  UpperCAmelCase__           =       model(__a				)
  self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)				)




 def 						UpperCamelCase__							(self , __a , __a , __a				)				->      Optional[int]:






  """simple docstring"""





  UpperCAmelCase__           =       VivitForVideoClassification(__a				)
  model.to(__a				)
  model.eval()

  UpperCAmelCase__           =       model(__a				)

  # verify the logits shape
  UpperCAmelCase__           =       torch.Size((self.batch_size, self.num_labels)				)
  self.parent.assertEqual(result.logits.shape , __a				)




 def 						UpperCamelCase__							(self				)				->      Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__           =       self.prepare_config_and_inputs()
  UpperCAmelCase__       ,					UpperCAmelCase__       ,					UpperCAmelCase__           =       config_and_inputs
  UpperCAmelCase__           =       {'pixel_values': pixel_values}
  return config, inputs_dict







@require_torch
class 					lowercase		( _UpperCamelCase				,       unittest.TestCase      ):



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE      							=       (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

 __SCREAMING_SNAKE_CASE      							=       False
 __SCREAMING_SNAKE_CASE      							=       False
 __SCREAMING_SNAKE_CASE      							=       False
 __SCREAMING_SNAKE_CASE      							=       False




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






  """simple docstring"""





  UpperCAmelCase__           =       VivitModelTester(self				)
  UpperCAmelCase__           =       ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37				)




 def 						UpperCamelCase__							(self , __a , __a , __a=False				)				->      int:






  """simple docstring"""





  UpperCAmelCase__           =       copy.deepcopy(__a				)

  if return_labels:
   if model_class in get_values(__a				):
    UpperCAmelCase__           =       torch.zeros(
        self.model_tester.batch_size , dtype=torch.long , device=__a				)

  return inputs_dict




 def 						UpperCamelCase__							(self				)				->      Tuple:






  """simple docstring"""





  self.config_tester.run_common_tests()




 @unittest.skip(reason='Vivit does not use inputs_embeds'				)
 def 						UpperCamelCase__							(self				)				->      str:






  """simple docstring"""





  pass




 def 						UpperCamelCase__							(self				)				->      Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__       ,					UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   UpperCAmelCase__           =       model_class(__a				)
   self.assertIsInstance(model.get_input_embeddings() , (nn.Module)				)
   UpperCAmelCase__           =       model.get_output_embeddings()
   self.assertTrue(x is None or isinstance(__a , nn.Linear				)				)




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






  """simple docstring"""





  UpperCAmelCase__       ,					UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   UpperCAmelCase__           =       model_class(__a				)
   UpperCAmelCase__           =       inspect.signature(model.forward				)
   # signature.parameters is an OrderedDict => so arg_names order is deterministic
   UpperCAmelCase__           =       [*signature.parameters.keys()]

   UpperCAmelCase__           =       ['pixel_values', 'head_mask']
   self.assertListEqual(arg_names[:2] , __a				)




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






  """simple docstring"""





  UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_model(*__a				)




 def 						UpperCamelCase__							(self				)				->      Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_video_classification(*__a				)




 @slow
 def 						UpperCamelCase__							(self				)				->      Optional[int]:






  """simple docstring"""





  for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   UpperCAmelCase__           =       VivitModel.from_pretrained(__a				)
   self.assertIsNotNone(__a				)




 def 						UpperCamelCase__							(self				)				->      Any:






  """simple docstring"""





  UpperCAmelCase__       ,					UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs_for_common()
  UpperCAmelCase__           =       True

  for model_class in self.all_model_classes:
   UpperCAmelCase__           =       self.model_tester.seq_length

   UpperCAmelCase__           =       True
   UpperCAmelCase__           =       False
   UpperCAmelCase__           =       True
   UpperCAmelCase__           =       model_class(__a				)
   model.to(__a				)
   model.eval()
   with torch.no_grad():
    UpperCAmelCase__           =       model(**self._prepare_for_class(__a , __a				)				)
   UpperCAmelCase__           =       outputs.attentions
   self.assertEqual(len(__a				) , self.model_tester.num_hidden_layers				)

   # check that output_attentions also work using config
   del inputs_dict["output_attentions"]
   UpperCAmelCase__           =       True
   UpperCAmelCase__           =       model_class(__a				)
   model.to(__a				)
   model.eval()
   with torch.no_grad():
    UpperCAmelCase__           =       model(**self._prepare_for_class(__a , __a				)				)
   UpperCAmelCase__           =       outputs.attentions
   self.assertEqual(len(__a				) , self.model_tester.num_hidden_layers				)

   self.assertListEqual(
       list(attentions[0].shape[-3:]				) , [self.model_tester.num_attention_heads, seq_len, seq_len] , )
   UpperCAmelCase__           =       len(__a				)

   # Check attention is always last and order is fine
   UpperCAmelCase__           =       True
   UpperCAmelCase__           =       True
   UpperCAmelCase__           =       model_class(__a				)
   model.to(__a				)
   model.eval()
   with torch.no_grad():
    UpperCAmelCase__           =       model(**self._prepare_for_class(__a , __a				)				)

   self.assertEqual(out_len + 1 , len(__a				)				)

   UpperCAmelCase__           =       outputs.attentions

   self.assertEqual(len(__a				) , self.model_tester.num_hidden_layers				)

   self.assertListEqual(
       list(self_attentions[0].shape[-3:]				) , [self.model_tester.num_attention_heads, seq_len, seq_len] , )




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






  """simple docstring"""





  def check_hidden_states_output(__a , __a , __a				):
   UpperCAmelCase__           =       model_class(__a				)
   model.to(__a				)
   model.eval()

   with torch.no_grad():
    UpperCAmelCase__           =       model(**self._prepare_for_class(__a , __a				)				)

   UpperCAmelCase__           =       outputs.hidden_states
   UpperCAmelCase__           =       self.model_tester.num_hidden_layers + 1
   self.assertEqual(len(__a				) , __a				)

   UpperCAmelCase__           =       self.model_tester.seq_length

   self.assertListEqual(
       list(hidden_states[0].shape[-2:]				) , [seq_length, self.model_tester.hidden_size] , )

  UpperCAmelCase__       ,					UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   UpperCAmelCase__           =       True
   check_hidden_states_output(__a , __a , __a				)

   # check that output_hidden_states also work using config
   del inputs_dict["output_hidden_states"]
   UpperCAmelCase__           =       True

   check_hidden_states_output(__a , __a , __a				)




 @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'				)
 def 						UpperCamelCase__							(self				)				->      List[str]:






  """simple docstring"""





  pass







def 		UpperCamelCase_(    ) ->				List[Any]:
 UpperCAmelCase__           =       hf_hub_download(
     repo_id='hf-internal-testing/spaghetti-video'						,					filename='eating_spaghetti_32_frames.npy'						,					repo_type='dataset'     )
 UpperCAmelCase__           =       np.load(snake_case__     )
 return list(snake_case__     )







@require_torch
@require_vision
class 					lowercase		( unittest.TestCase      ):



 '''simple docstring'''


 @cached_property
 def 						UpperCamelCase__							(self				)				->      List[str]:






  """simple docstring"""





  return VivitImageProcessor() if is_vision_available() else None




 @slow
 def 						UpperCamelCase__							(self				)				->      str:






  """simple docstring"""





  UpperCAmelCase__           =       VivitForVideoClassification.from_pretrained('google/vivit-b-16x2-kinetics400'				).to(__a				)

  UpperCAmelCase__           =       self.default_image_processor
  UpperCAmelCase__           =       prepare_video()
  UpperCAmelCase__           =       image_processor(__a , return_tensors='pt'				).to(__a				)

  # forward pass
  with torch.no_grad():
   UpperCAmelCase__           =       model(**__a				)

  # verify the logits
  UpperCAmelCase__           =       torch.Size((1, 400)				)
  self.assertEqual(outputs.logits.shape , __a				)

  # taken from original model
  UpperCAmelCase__           =       torch.tensor([-1.05_43, 2.07_64, -0.21_04, 0.44_39, -0.96_58]				).to(__a				)

  self.assertTrue(torch.allclose(outputs.logits[0, :5] , __a , atol=1E-4				)				)



