"""simple docstring"""





from ...configuration_utils import PretrainedConfig
from ...utils import logging


_UpperCamelCase     :		int											=					logging.get_logger(__name__)

_UpperCamelCase     :		Dict											=					{
    "s-JoL/Open-Llama-V1": "https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json",
}


class   UpperCAmelCase_			(					_a):
      lowerCamelCase__	:					Optional[int]										=						"open-llama"


      def __init__(     self	,    a=1_0_0_0_0_0	,    a=4_0_9_6	,    a=1_1_0_0_8	,    a=3_2	,    a=3_2	,    a="silu"	,    a=2_0_4_8	,    a=0.02	,    a=1e-6	,    a=True	,    a=0	,    a=1	,    a=2	,    a=False	,    a=True	,    a=0.1	,    a=0.1	,    a=True	,    a=True	,    a=None	,    **a	,    ) ->      Optional[Any]:
             lowercase__    :	List[Any]     					=			vocab_size
             lowercase__    :	Union[str, Any]     					=			max_position_embeddings
             lowercase__    :	List[str]     					=			hidden_size
             lowercase__    :	Union[str, Any]     					=			intermediate_size
             lowercase__    :	Dict     					=			num_hidden_layers
             lowercase__    :	Dict     					=			num_attention_heads
             lowercase__    :	str     					=			hidden_act
             lowercase__    :	Union[str, Any]     					=			initializer_range
             lowercase__    :	Any     					=			rms_norm_eps
             lowercase__    :	List[Any]     					=			use_cache
             lowercase__    :	Any     					=			kwargs.pop(
                 'use_memorry_efficient_attention'	,    a							)
             lowercase__    :	Dict     					=			hidden_dropout_prob
             lowercase__    :	List[str]     					=			attention_dropout_prob
             lowercase__    :	Tuple     					=			use_stable_embedding
             lowercase__    :	Optional[Any]     					=			shared_input_output_embedding
             lowercase__    :	Optional[Any]     					=			rope_scaling
             self._rope_scaling_validation()

             super().__init__(
                 pad_token_id=a	,    bos_token_id=a	,    eos_token_id=a	,    tie_word_embeddings=a	,    **a	,    )


      def 	_UpperCAmelCase (     self							) ->      str:
             if self.rope_scaling is None:
                    return

             if not isinstance(self.rope_scaling	,    a							) or len(self.rope_scaling							) != 2:
                    raise ValueError(
                        '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '
                        f"""got {self.rope_scaling}"""							)
             lowercase__    :	Dict     					=			self.rope_scaling.get('type'	,    a							)
             lowercase__    :	Union[str, Any]     					=			self.rope_scaling.get('factor'	,    a							)
             if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
                    raise ValueError(
                        f"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"""							)
             if rope_scaling_factor is None or not isinstance(a	,    a							) or rope_scaling_factor <= 1.0:
                    raise ValueError(f"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}"""							)


"""simple docstring"""





import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VideoMAEConfig
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
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch
       from torch import nn

       from transformers import (
           MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
           VideoMAEForPreTraining,
           VideoMAEForVideoClassification,
           VideoMAEModel,
       )
       from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from transformers import VideoMAEImageProcessor


class   UpperCAmelCase_			:


      def __init__(     self	,    a	,    a=1_3	,    a=1_0	,    a=3	,    a=2	,    a=2	,    a=2	,    a=True	,    a=True	,    a=3_2	,    a=5	,    a=4	,    a=3_7	,    a="gelu"	,    a=0.1	,    a=0.1	,    a=1_0	,    a=0.02	,    a=0.9	,    a=None	,    ) ->      Optional[Any]:
             lowercase__    :	str     					=			parent
             lowercase__    :	int     					=			batch_size
             lowercase__    :	Union[str, Any]     					=			image_size
             lowercase__    :	Optional[Any]     					=			num_channels
             lowercase__    :	Dict     					=			patch_size
             lowercase__    :	Tuple     					=			tubelet_size
             lowercase__    :	Optional[int]     					=			num_frames
             lowercase__    :	Optional[int]     					=			is_training
             lowercase__    :	int     					=			use_labels
             lowercase__    :	Optional[int]     					=			hidden_size
             lowercase__    :	Union[str, Any]     					=			num_hidden_layers
             lowercase__    :	Optional[int]     					=			num_attention_heads
             lowercase__    :	Any     					=			intermediate_size
             lowercase__    :	str     					=			hidden_act
             lowercase__    :	List[Any]     					=			hidden_dropout_prob
             lowercase__    :	str     					=			attention_probs_dropout_prob
             lowercase__    :	Union[str, Any]     					=			type_sequence_label_size
             lowercase__    :	List[Any]     					=			initializer_range
             lowercase__    :	str     					=			mask_ratio
             lowercase__    :	Optional[Any]     					=			scope

             # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
             lowercase__    :	Optional[Any]     					=			(image_size // patch_size) ** 2
             lowercase__    :	str     					=			(num_frames // tubelet_size) * self.num_patches_per_frame

             # use this variable to define bool_masked_pos
             lowercase__    :	str     					=			int(mask_ratio * self.seq_length							)


      def 	_UpperCAmelCase (     self							) ->      Tuple:
             lowercase__    :	int     					=			floats_tensor(
                 [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]							)

             lowercase__    :	int     					=			None
             if self.use_labels:
                    lowercase__    :	Optional[Any]     					=			ids_tensor([self.batch_size]	,    self.type_sequence_label_size							)

             lowercase__    :	Dict     					=			self.get_config()

             return config, pixel_values, labels


      def 	_UpperCAmelCase (     self							) ->      Tuple:
             return VideoMAEConfig(
                 image_size=self.image_size	,    patch_size=self.patch_size	,    num_channels=self.num_channels	,    num_frames=self.num_frames	,    tubelet_size=self.tubelet_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	,    is_decoder=a	,    initializer_range=self.initializer_range	,    )


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a							) ->      Optional[int]:
             lowercase__    :	Dict     					=			VideoMAEModel(config=a							)
             model.to(a							)
             model.eval()
             lowercase__    :	Tuple     					=			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							) ->      Union[str, Any]:
             lowercase__    :	str     					=			VideoMAEForPreTraining(a							)
             model.to(a							)
             model.eval()
             # important: each video needs to have the same number of masked patches
             # hence we define a single mask, which we then repeat for each example in the batch
             lowercase__    :	Any     					=			torch.ones((self.num_masks,)							)
             lowercase__    :	str     					=			torch.cat([mask, torch.zeros(self.seq_length - mask.size(0							)							)]							)
             lowercase__    :	Optional[int]     					=			mask.expand(self.batch_size	,    -1							).bool()

             lowercase__    :	str     					=			model(a	,    a							)
             # model only returns predictions for masked patches
             lowercase__    :	str     					=			mask.sum().item()
             lowercase__    :	int     					=			3 * self.tubelet_size * self.patch_size**2
             self.parent.assertEqual(result.logits.shape	,    (self.batch_size, num_masked_patches, decoder_num_labels)							)


      def 	_UpperCAmelCase (     self							) ->      str:
             lowercase__    :	Dict     					=			self.prepare_config_and_inputs()
             lowercase__					,   lowercase__					,   lowercase__    :	Union[str, Any]     					=			config_and_inputs
             lowercase__    :	List[str]     					=			{'pixel_values': pixel_values}
             return config, inputs_dict





@require_torch
class   UpperCAmelCase_			(					_a				,							_a				,							unittest.TestCase):
      lowerCamelCase__	:					Tuple										=						(
          (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
      )
      lowerCamelCase__	:					Optional[int]										=						(
          {"feature-extraction": VideoMAEModel, "video-classification": VideoMAEForVideoClassification}
          if is_torch_available()
          else {}
      )

      lowerCamelCase__	:					Any										=						False
      lowerCamelCase__	:					Any										=						False
      lowerCamelCase__	:					Union[str, Any]										=						False
      lowerCamelCase__	:					str										=						False


      def 	_UpperCAmelCase (     self							) ->      Tuple:
             lowercase__    :	Optional[Any]     					=			VideoMAEModelTester(self							)
             lowercase__    :	Optional[Any]     					=			ConfigTester(self	,    config_class=a	,    has_text_modality=a	,    hidden_size=3_7							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a=False							) ->      Optional[int]:
             lowercase__    :	Union[str, Any]     					=			copy.deepcopy(a							)

             if model_class == VideoMAEForPreTraining:
                    # important: each video needs to have the same number of masked patches
                    # hence we define a single mask, which we then repeat for each example in the batch
                    lowercase__    :	Optional[Any]     					=			torch.ones((self.model_tester.num_masks,)							)
                    lowercase__    :	Any     					=			torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0							)							)]							)
                    lowercase__    :	Any     					=			mask.expand(self.model_tester.batch_size	,    -1							).bool()
                    lowercase__    :	Union[str, Any]     					=			bool_masked_pos.to(a							)

             if return_labels:
                    if model_class in [
                        *get_values(a							),
                    ]:
                           lowercase__    :	Dict     					=			torch.zeros(
                               self.model_tester.batch_size	,    dtype=torch.long	,    device=a							)

             return inputs_dict


      def 	_UpperCAmelCase (     self							) ->      Tuple:
             self.config_tester.run_common_tests()


      @unittest.skip(reason='VideoMAE does not use inputs_embeds'							)
      def 	_UpperCAmelCase (     self							) ->      Dict:
             pass


      def 	_UpperCAmelCase (     self							) ->      List[Any]:
             lowercase__					,   lowercase__    :	Optional[int]     					=			self.model_tester.prepare_config_and_inputs_for_common()

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


      def 	_UpperCAmelCase (     self							) ->      Optional[int]:
             lowercase__					,   lowercase__    :	Any     					=			self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    lowercase__    :	List[str]     					=			model_class(a							)
                    lowercase__    :	int     					=			inspect.signature(model.forward							)
                    # signature.parameters is an OrderedDict => so arg_names order is deterministic
                    lowercase__    :	Optional[Any]     					=			[*signature.parameters.keys()]

                    lowercase__    :	int     					=			['pixel_values']
                    self.assertListEqual(arg_names[:1]	,    a							)


      def 	_UpperCAmelCase (     self							) ->      Optional[Any]:
             lowercase__    :	List[str]     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*a							)


      def 	_UpperCAmelCase (     self							) ->      Tuple:
             lowercase__    :	Union[str, Any]     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_pretraining(*a							)


      @slow
      def 	_UpperCAmelCase (     self							) ->      str:
             for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    lowercase__    :	List[Any]     					=			VideoMAEModel.from_pretrained(a							)
                    self.assertIsNotNone(a							)


      def 	_UpperCAmelCase (     self							) ->      Optional[Any]:
             if not self.has_attentions:
                    pass

             else:
                    lowercase__					,   lowercase__    :	Union[str, Any]     					=			self.model_tester.prepare_config_and_inputs_for_common()
                    lowercase__    :	str     					=			True

                    for model_class in self.all_model_classes:
                           lowercase__    :	Union[str, Any]     					=			self.model_tester.seq_length - self.model_tester.num_masks
                           lowercase__    :	Any     					=			(
                               num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
                           )

                           lowercase__    :	Optional[Any]     					=			True
                           lowercase__    :	int     					=			False
                           lowercase__    :	Any     					=			True
                           lowercase__    :	List[str]     					=			model_class(a							)
                           model.to(a							)
                           model.eval()
                           with torch.no_grad():
                                  lowercase__    :	Optional[int]     					=			model(**self._prepare_for_class(a	,    a							)							)
                           lowercase__    :	Dict     					=			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"]
                           lowercase__    :	str     					=			True
                           lowercase__    :	List[str]     					=			model_class(a							)
                           model.to(a							)
                           model.eval()
                           with torch.no_grad():
                                  lowercase__    :	List[Any]     					=			model(**self._prepare_for_class(a	,    a							)							)
                           lowercase__    :	Optional[Any]     					=			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]	,    )
                           lowercase__    :	List[str]     					=			len(a							)

                           # Check attention is always last and order is fine
                           lowercase__    :	Optional[int]     					=			True
                           lowercase__    :	List[str]     					=			True
                           lowercase__    :	int     					=			model_class(a							)
                           model.to(a							)
                           model.eval()
                           with torch.no_grad():
                                  lowercase__    :	List[str]     					=			model(**self._prepare_for_class(a	,    a							)							)

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

                           lowercase__    :	int     					=			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]:
             def check_hidden_states_output(a	,    a	,    a							):
                    lowercase__    :	Optional[int]     					=			model_class(a							)
                    model.to(a							)
                    model.eval()

                    with torch.no_grad():
                           lowercase__    :	Optional[Any]     					=			model(**self._prepare_for_class(a	,    a							)							)

                    lowercase__    :	Optional[int]     					=			outputs.hidden_states
                    lowercase__    :	List[Any]     					=			self.model_tester.num_hidden_layers + 1
                    self.assertEqual(len(a							)	,    a							)

                    lowercase__    :	Optional[Any]     					=			self.model_tester.seq_length - self.model_tester.num_masks
                    lowercase__    :	Union[str, Any]     					=			num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length

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

             lowercase__					,   lowercase__    :	List[Any]     					=			self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    lowercase__    :	Tuple     					=			True
                    check_hidden_states_output(a	,    a	,    a							)

                    # check that output_hidden_states also work using config
                    del inputs_dict["output_hidden_states"]
                    lowercase__    :	Union[str, Any]     					=			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[Any]:
             pass





def        a_  (   ):





       '''simple docstring'''

       lowercase__    :	int     					=			hf_hub_download(
           repo_id='hf-internal-testing/spaghetti-video'     ,				filename='eating_spaghetti.npy'     ,				repo_type='dataset'  )
       lowercase__    :	str     					=			np.load(_lowerCAmelCase  )
       return list(_lowerCAmelCase  )






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


      @cached_property
      def 	_UpperCAmelCase (     self							) ->      Optional[Any]:
             # logits were tested with a different mean and std, so we use the same here
             return (
                 VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]	,    image_std=[0.5, 0.5, 0.5]							)
                 if is_vision_available()
                 else None
             )


      @slow
      def 	_UpperCAmelCase (     self							) ->      int:
             lowercase__    :	Dict     					=			VideoMAEForVideoClassification.from_pretrained('MCG-NJU/videomae-base-finetuned-kinetics'							).to(
                 a							)

             lowercase__    :	str     					=			self.default_image_processor
             lowercase__    :	List[str]     					=			prepare_video()
             lowercase__    :	int     					=			image_processor(a	,    return_tensors='pt'							).to(a							)

             # forward pass
             with torch.no_grad():
                    lowercase__    :	Union[str, Any]     					=			model(**a							)

             # verify the logits
             lowercase__    :	str     					=			torch.Size((1, 4_0_0)							)
             self.assertEqual(outputs.logits.shape	,    a							)

             lowercase__    :	List[Any]     					=			torch.tensor([0.3_669, -0.0_688, -0.2_421]							).to(a							)

             self.assertTrue(torch.allclose(outputs.logits[0, :3]	,    a	,    atol=1e-4							)							)


      @slow
      def 	_UpperCAmelCase (     self							) ->      List[str]:
             lowercase__    :	Optional[int]     					=			VideoMAEForPreTraining.from_pretrained('MCG-NJU/videomae-base-short'							).to(a							)

             lowercase__    :	Optional[Any]     					=			self.default_image_processor
             lowercase__    :	List[str]     					=			prepare_video()
             lowercase__    :	str     					=			image_processor(a	,    return_tensors='pt'							).to(a							)

             # add boolean mask, indicating which patches to mask
             lowercase__    :	Union[str, Any]     					=			hf_hub_download(repo_id='hf-internal-testing/bool-masked-pos'	,    filename='bool_masked_pos.pt'							)
             lowercase__    :	str     					=			torch.load(a							)

             # forward pass
             with torch.no_grad():
                    lowercase__    :	List[Any]     					=			model(**a							)

             # verify the logits
             lowercase__    :	Dict     					=			torch.Size([1, 1_4_0_8, 1_5_3_6]							)
             lowercase__    :	List[str]     					=			torch.tensor(
                 [[0.7_994, 0.9_612, 0.8_508], [0.7_401, 0.8_958, 0.8_302], [0.5_862, 0.7_468, 0.7_325]]	,    device=a							)
             self.assertEqual(outputs.logits.shape	,    a							)
             self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]	,    a	,    atol=1e-4							)							)

             # verify the loss (`config.norm_pix_loss` = `True`)
             lowercase__    :	List[Any]     					=			torch.tensor([0.5_142]	,    device=a							)
             self.assertTrue(torch.allclose(outputs.loss	,    a	,    atol=1e-4							)							)

             # verify the loss (`config.norm_pix_loss` = `False`)
             lowercase__    :	Tuple     					=			VideoMAEForPreTraining.from_pretrained('MCG-NJU/videomae-base-short'	,    norm_pix_loss=a							).to(
                 a							)

             with torch.no_grad():
                    lowercase__    :	Any     					=			model(**a							)

             lowercase__    :	List[Any]     					=			torch.tensor(torch.tensor([0.6_469]							)	,    device=a							)
             self.assertTrue(torch.allclose(outputs.loss	,    a	,    atol=1e-4							)							)

