






"""simple docstring"""



import colorsys
import io

import cva
import matplotlib as mpl
import matplotlib.colors as mplc
import matplotlib.figure as mplfigure
import numpy as np
import torch
from matplotlib.backends.backend_agg import FigureCanvasAgg

from utils import img_tensorize


_snake_case       :      Dict       =					1_000




class        __lowercase:






						def __init__(					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE=1.2    ,						_SCREAMING_SNAKE_CASE="g"    ,						_SCREAMING_SNAKE_CASE=0.5    ,						_SCREAMING_SNAKE_CASE="-"    ,						_SCREAMING_SNAKE_CASE="test_out.jpg"    ,						_SCREAMING_SNAKE_CASE=True    ,						_SCREAMING_SNAKE_CASE=False    ,						_SCREAMING_SNAKE_CASE=None    ,						_SCREAMING_SNAKE_CASE=None    ,						_SCREAMING_SNAKE_CASE=0.7    ,						)			->  List[Any]:




											"""simple docstring"""





											if isinstance(_SCREAMING_SNAKE_CASE    ,						torch.Tensor):
																lowerCamelCase__				=img.numpy().astype('np.uint8')
											if isinstance(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE):
																lowerCamelCase__				=img_tensorize(_SCREAMING_SNAKE_CASE)
											assert isinstance(_SCREAMING_SNAKE_CASE    ,						np.ndarray)

											lowerCamelCase__				,     lowerCamelCase__				=img.shape[1], img.shape[0]
											lowerCamelCase__				=mplfigure.Figure(frameon=_SCREAMING_SNAKE_CASE)
											lowerCamelCase__				=fig.get_dpi()
											lowerCamelCase__				=(width * scale + 1E-2) / dpi
											lowerCamelCase__				=(height * scale + 1E-2) / dpi
											fig.set_size_inches(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
											lowerCamelCase__				=fig.add_axes([0.0, 0.0, 1.0, 1.0])
											ax.axis('off')
											ax.set_xlim(0.0    ,						_SCREAMING_SNAKE_CASE)
											ax.set_ylim(_SCREAMING_SNAKE_CASE)

											lowerCamelCase__				=saveas
											lowerCamelCase__				=rgb
											lowerCamelCase__				=pynb
											lowerCamelCase__				=img
											lowerCamelCase__				=edgecolor
											lowerCamelCase__				=0.5
											lowerCamelCase__				=linestyle
											lowerCamelCase__				=int(np.sqrt(min(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)) * scale // 3)
											lowerCamelCase__				=width
											lowerCamelCase__				=height
											lowerCamelCase__				=scale
											lowerCamelCase__				=fig
											lowerCamelCase__				=ax
											lowerCamelCase__				=pad
											lowerCamelCase__				=idaobj
											lowerCamelCase__				=idaattr
											lowerCamelCase__				=FigureCanvasAgg(_SCREAMING_SNAKE_CASE)






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE=None)			->  str:




											"""simple docstring"""





											if color is None:
																lowerCamelCase__				=self.edgecolor
											((lowerCamelCase__)				,     (lowerCamelCase__)				,     (lowerCamelCase__)				,     (lowerCamelCase__))				=box
											lowerCamelCase__				=xa - xa
											lowerCamelCase__				=ya - ya
											self.ax.add_patch(
											    mpl.patches.Rectangle(
											        (xa, ya)    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						fill=_SCREAMING_SNAKE_CASE    ,						edgecolor=_SCREAMING_SNAKE_CASE    ,						linewidth=self.font_size // 3    ,						alpha=self.alpha    ,						linestyle=self.linestyle    ,						))






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE=None    ,						_SCREAMING_SNAKE_CASE=None    ,						_SCREAMING_SNAKE_CASE=None    ,						_SCREAMING_SNAKE_CASE=None)			->  int:




											"""simple docstring"""





											if len(boxes.shape) > 2:
																lowerCamelCase__				=boxes[0]
											if len(obj_ids.shape) > 1:
																lowerCamelCase__				=obj_ids[0]
											if len(obj_scores.shape) > 1:
																lowerCamelCase__				=obj_scores[0]
											if len(attr_ids.shape) > 1:
																lowerCamelCase__				=attr_ids[0]
											if len(attr_scores.shape) > 1:
																lowerCamelCase__				=attr_scores[0]
											if isinstance(_SCREAMING_SNAKE_CASE    ,						torch.Tensor):
																lowerCamelCase__				=boxes.numpy()
											if isinstance(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE):
																lowerCamelCase__				=np.array(_SCREAMING_SNAKE_CASE)
											assert isinstance(_SCREAMING_SNAKE_CASE    ,						np.ndarray)
											lowerCamelCase__				=np.prod(boxes[:, 2:] - boxes[:, :2]    ,						axis=1)
											lowerCamelCase__				=np.argsort(-areas).tolist()
											lowerCamelCase__				=boxes[sorted_idxs] if boxes is not None else None
											lowerCamelCase__				=obj_ids[sorted_idxs] if obj_ids is not None else None
											lowerCamelCase__				=obj_scores[sorted_idxs] if obj_scores is not None else None
											lowerCamelCase__				=attr_ids[sorted_idxs] if attr_ids is not None else None
											lowerCamelCase__				=attr_scores[sorted_idxs] if attr_scores is not None else None

											lowerCamelCase__				=[self._random_color(maximum=1) for _ in range(len(_SCREAMING_SNAKE_CASE))]
											lowerCamelCase__				=[assigned_colors[idx] for idx in sorted_idxs]
											if obj_ids is not None:
																lowerCamelCase__				=self._create_text_labels_attr(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
																for i in range(len(_SCREAMING_SNAKE_CASE)):
																					lowerCamelCase__				=assigned_colors[i]
																					self.add_box(boxes[i]    ,						_SCREAMING_SNAKE_CASE)
																					self.draw_labels(labels[i]    ,						boxes[i]    ,						_SCREAMING_SNAKE_CASE)






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)			->  str:




											"""simple docstring"""





											lowerCamelCase__				,     lowerCamelCase__				,     lowerCamelCase__				,     lowerCamelCase__				=box
											lowerCamelCase__				=(xa, ya)
											lowerCamelCase__				=(ya - ya) * (xa - xa)
											lowerCamelCase__				=_SMALL_OBJ * self.scale
											if instance_area < small or ya - ya < 40 * self.scale:
																if ya >= self.height - 5:
																					lowerCamelCase__				=(xa, ya)
																else:
																					lowerCamelCase__				=(xa, ya)

											lowerCamelCase__				=(ya - ya) / np.sqrt(self.height * self.width)
											lowerCamelCase__				=self._change_color_brightness(_SCREAMING_SNAKE_CASE    ,						brightness_factor=0.7)
											lowerCamelCase__				=np.clip((height_ratio - 0.02) / 0.08 + 1    ,						1.2    ,						2)
											font_size *= 0.75 * self.font_size

											self.draw_text(
											    text=_SCREAMING_SNAKE_CASE    ,						position=_SCREAMING_SNAKE_CASE    ,						color=_SCREAMING_SNAKE_CASE    ,						)






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE="g"    ,						_SCREAMING_SNAKE_CASE="left"    ,						)			->  List[str]:




											"""simple docstring"""





											lowerCamelCase__				=0
											lowerCamelCase__				=self.font_size
											lowerCamelCase__				=np.maximum(list(mplc.to_rgb(_SCREAMING_SNAKE_CASE))    ,						0.2)
											lowerCamelCase__				=max(0.8    ,						np.max(_SCREAMING_SNAKE_CASE))
											lowerCamelCase__				={
											    'facecolor': 'black',
											    'alpha': self.alpha,
											    'pad': self.pad,
											    'edgecolor': 'none',
											}
											lowerCamelCase__				,     lowerCamelCase__				=position
											self.ax.text(
											    _SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						size=font_size * self.scale    ,						family='sans-serif'    ,						bbox=_SCREAMING_SNAKE_CASE    ,						verticalalignment='top'    ,						horizontalalignment=_SCREAMING_SNAKE_CASE    ,						color=_SCREAMING_SNAKE_CASE    ,						zorder=10    ,						rotation=_SCREAMING_SNAKE_CASE    ,						)






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE=None)			->  Optional[int]:




											"""simple docstring"""





											if saveas is None:
																lowerCamelCase__				=self.saveas
											if saveas.lower().endswith('.jpg') or saveas.lower().endswith('.png'):
																cva.imwrite(
																    _SCREAMING_SNAKE_CASE    ,						self._get_buffer()[:, :, ::-1]    ,						)
											else:
																self.fig.savefig(_SCREAMING_SNAKE_CASE)






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)			->  Optional[Any]:




											"""simple docstring"""





											lowerCamelCase__				=[self.idaobj[i] for i in classes]
											lowerCamelCase__				=[self.idaattr[i] for i in attr_classes]
											lowerCamelCase__				=[
											    F"{label} {score:.2f} {attr} {attr_score:.2f}"
											    for label, score, attr, attr_score in zip(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)
											]
											return labels






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)			->  Any:




											"""simple docstring"""





											lowerCamelCase__				=[self.idaobj[i] for i in classes]
											if scores is not None:
																if labels is None:
																					lowerCamelCase__				=['{:.0f}%'.format(s * 1_00) for s in scores]
																else:
																					lowerCamelCase__				=['{} {:.0f}%'.format(_SCREAMING_SNAKE_CASE    ,						s * 1_00) for li, s in zip(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)]
											return labels






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE=2_55)			->  Optional[int]:




											"""simple docstring"""





											lowerCamelCase__				=np.random.randint(0    ,						len(_COLORS))
											lowerCamelCase__				=_COLORS[idx] * maximum
											if not self.rgb:
																lowerCamelCase__				=ret[::-1]
											return ret






						def 		lowerCAmelCase   (					self)			->  Dict:




											"""simple docstring"""





											if not self.pynb:
																lowerCamelCase__				,     lowerCamelCase__				=self.canvas.print_to_buffer()
																if (width, height) != (self.width, self.height):
																					lowerCamelCase__				=cva.resize(self.img    ,						(width, height))
																else:
																					lowerCamelCase__				=self.img
											else:
																lowerCamelCase__				=io.BytesIO()  # works for cairo backend
																self.canvas.print_rgba(_SCREAMING_SNAKE_CASE)
																lowerCamelCase__				,     lowerCamelCase__				=self.width, self.height
																lowerCamelCase__				=buf.getvalue()
																lowerCamelCase__				=self.img

											lowerCamelCase__				=np.frombuffer(_SCREAMING_SNAKE_CASE    ,						dtype='uint8')
											lowerCamelCase__				=buffer.reshape(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						4)
											lowerCamelCase__				,     lowerCamelCase__				=np.split(_SCREAMING_SNAKE_CASE    ,						[3]    ,						axis=2)

											try:
																import numexpr as ne  # fuse them with numexpr

																lowerCamelCase__				=ne.evaluate('img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)')
											except ImportError:
																lowerCamelCase__				=alpha.astype('float32') / 255.0
																lowerCamelCase__				=img * (1 - alpha) + rgb * alpha

											return visualized_image.astype('uint8')






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)			->  Tuple:




											"""simple docstring"""





											assert brightness_factor >= -1.0 and brightness_factor <= 1.0
											lowerCamelCase__				=mplc.to_rgb(_SCREAMING_SNAKE_CASE)
											lowerCamelCase__				=colorsys.rgb_to_hls(*mplc.to_rgb(_SCREAMING_SNAKE_CASE))
											lowerCamelCase__				=polygon_color[1] + (brightness_factor * polygon_color[1])
											lowerCamelCase__				=0.0 if modified_lightness < 0.0 else modified_lightness
											lowerCamelCase__				=1.0 if modified_lightness > 1.0 else modified_lightness
											lowerCamelCase__				=colorsys.hls_to_rgb(polygon_color[0]    ,						_SCREAMING_SNAKE_CASE    ,						polygon_color[2])
											return modified_color



_snake_case       :      List[Any]       =					(
    np.array(
        [
            0.000,
            0.447,
            0.741,
            0.850,
            0.325,
            0.098,
            0.929,
            0.694,
            0.125,
            0.494,
            0.184,
            0.556,
            0.466,
            0.674,
            0.188,
            0.301,
            0.745,
            0.933,
            0.635,
            0.078,
            0.184,
            0.300,
            0.300,
            0.300,
            0.600,
            0.600,
            0.600,
            1.000,
            0.000,
            0.000,
            1.000,
            0.500,
            0.000,
            0.749,
            0.749,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            1.000,
            0.667,
            0.000,
            1.000,
            0.333,
            0.333,
            0.000,
            0.333,
            0.667,
            0.000,
            0.333,
            1.000,
            0.000,
            0.667,
            0.333,
            0.000,
            0.667,
            0.667,
            0.000,
            0.667,
            1.000,
            0.000,
            1.000,
            0.333,
            0.000,
            1.000,
            0.667,
            0.000,
            1.000,
            1.000,
            0.000,
            0.000,
            0.333,
            0.500,
            0.000,
            0.667,
            0.500,
            0.000,
            1.000,
            0.500,
            0.333,
            0.000,
            0.500,
            0.333,
            0.333,
            0.500,
            0.333,
            0.667,
            0.500,
            0.333,
            1.000,
            0.500,
            0.667,
            0.000,
            0.500,
            0.667,
            0.333,
            0.500,
            0.667,
            0.667,
            0.500,
            0.667,
            1.000,
            0.500,
            1.000,
            0.000,
            0.500,
            1.000,
            0.333,
            0.500,
            1.000,
            0.667,
            0.500,
            1.000,
            1.000,
            0.500,
            0.000,
            0.333,
            1.000,
            0.000,
            0.667,
            1.000,
            0.000,
            1.000,
            1.000,
            0.333,
            0.000,
            1.000,
            0.333,
            0.333,
            1.000,
            0.333,
            0.667,
            1.000,
            0.333,
            1.000,
            1.000,
            0.667,
            0.000,
            1.000,
            0.667,
            0.333,
            1.000,
            0.667,
            0.667,
            1.000,
            0.667,
            1.000,
            1.000,
            1.000,
            0.000,
            1.000,
            1.000,
            0.333,
            1.000,
            1.000,
            0.667,
            1.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.167,
            0.000,
            0.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.167,
            0.000,
            0.000,
            0.333,
            0.000,
            0.000,
            0.500,
            0.000,
            0.000,
            0.667,
            0.000,
            0.000,
            0.833,
            0.000,
            0.000,
            1.000,
            0.000,
            0.000,
            0.000,
            0.143,
            0.143,
            0.143,
            0.857,
            0.857,
            0.857,
            1.000,
            1.000,
            1.000,
        ]
    )
    .astype(np.floataa)
    .reshape(-1, 3)
)







"""simple docstring"""



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:






						def __init__(					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE=2    ,						_SCREAMING_SNAKE_CASE=True    ,						_SCREAMING_SNAKE_CASE=True    ,						_SCREAMING_SNAKE_CASE=10    ,						_SCREAMING_SNAKE_CASE=10    ,						_SCREAMING_SNAKE_CASE=8    ,						_SCREAMING_SNAKE_CASE=[2, 4, 4]    ,						_SCREAMING_SNAKE_CASE=3    ,						_SCREAMING_SNAKE_CASE=7_68    ,						_SCREAMING_SNAKE_CASE=5    ,						_SCREAMING_SNAKE_CASE=4    ,						_SCREAMING_SNAKE_CASE=37    ,						_SCREAMING_SNAKE_CASE="gelu_fast"    ,						_SCREAMING_SNAKE_CASE=0.0    ,						_SCREAMING_SNAKE_CASE=0.0    ,						_SCREAMING_SNAKE_CASE=0.02    ,						_SCREAMING_SNAKE_CASE=1E-06    ,						_SCREAMING_SNAKE_CASE=True    ,						_SCREAMING_SNAKE_CASE=None    ,						)			->  Dict:




											"""simple docstring"""





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

											lowerCamelCase__				=(
											    (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 		lowerCAmelCase   (					self)			->  Union[str, Any]:




											"""simple docstring"""





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

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

											lowerCamelCase__				=self.get_config()

											return config, pixel_values, labels






						def 		lowerCAmelCase   (					self)			->  Dict:




											"""simple docstring"""





											lowerCamelCase__				=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    ,						)
											lowerCamelCase__				=self.num_labels
											return config






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)			->  int:




											"""simple docstring"""





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






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)			->  str:




											"""simple docstring"""





											lowerCamelCase__				=VivitForVideoClassification(_SCREAMING_SNAKE_CASE)
											model.to(_SCREAMING_SNAKE_CASE)
											model.eval()

											lowerCamelCase__				=model(_SCREAMING_SNAKE_CASE)

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






						def 		lowerCAmelCase   (					self)			->  Dict:




											"""simple docstring"""





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




@require_torch
class        __lowercase(       _UpperCamelCase						,							unittest.TestCase  ):
						lowerCAmelCase_		:							str=       (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

						lowerCAmelCase_		:							str=       False
						lowerCAmelCase_		:							Tuple=       False
						lowerCAmelCase_		:							Union[str, Any]=       False
						lowerCAmelCase_		:							Dict=       False






						def 		lowerCAmelCase   (					self)			->  List[str]:




											"""simple docstring"""





											lowerCamelCase__				=VivitModelTester(self)
											lowerCamelCase__				=ConfigTester(self    ,						config_class=_SCREAMING_SNAKE_CASE    ,						has_text_modality=_SCREAMING_SNAKE_CASE    ,						hidden_size=37)






						def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE=False)			->  Optional[int]:




											"""simple docstring"""





											lowerCamelCase__				=copy.deepcopy(_SCREAMING_SNAKE_CASE)

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

											return inputs_dict






						def 		lowerCAmelCase   (					self)			->  Tuple:




											"""simple docstring"""





											self.config_tester.run_common_tests()






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




											"""simple docstring"""





											pass






						def 		lowerCAmelCase   (					self)			->  str:




											"""simple docstring"""





											lowerCamelCase__				,     lowerCamelCase__				=self.model_tester.prepare_config_and_inputs_for_common()

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






						def 		lowerCAmelCase   (					self)			->  Dict:




											"""simple docstring"""





											lowerCamelCase__				,     lowerCamelCase__				=self.model_tester.prepare_config_and_inputs_for_common()

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

																lowerCamelCase__				=['pixel_values', 'head_mask']
																self.assertListEqual(arg_names[:2]    ,						_SCREAMING_SNAKE_CASE)






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




											"""simple docstring"""





											lowerCamelCase__				=self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE)






						def 		lowerCAmelCase   (					self)			->  str:




											"""simple docstring"""





											lowerCamelCase__				=self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_video_classification(*_SCREAMING_SNAKE_CASE)






						@slow
						def 		lowerCAmelCase   (					self)			->  Tuple:




											"""simple docstring"""





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






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




											"""simple docstring"""





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

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

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

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

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

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

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

																lowerCamelCase__				=outputs.attentions

																self.assertEqual(len(_SCREAMING_SNAKE_CASE)    ,						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 		lowerCAmelCase   (					self)			->  Dict:




											"""simple docstring"""





											def check_hidden_states_output(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE):
																lowerCamelCase__				=model_class(_SCREAMING_SNAKE_CASE)
																model.to(_SCREAMING_SNAKE_CASE)
																model.eval()

																with torch.no_grad():
																					lowerCamelCase__				=model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE))

																lowerCamelCase__				=outputs.hidden_states
																lowerCamelCase__				=self.model_tester.num_hidden_layers + 1
																self.assertEqual(len(_SCREAMING_SNAKE_CASE)    ,						_SCREAMING_SNAKE_CASE)

																lowerCamelCase__				=self.model_tester.seq_length

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

											lowerCamelCase__				,     lowerCamelCase__				=self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																lowerCamelCase__				=True
																check_hidden_states_output(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)

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

																check_hidden_states_output(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)






						@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
						def 		lowerCAmelCase   (					self)			->  Dict:




											"""simple docstring"""





											pass




def 						lowerCamelCase_				(  ):
					lowerCamelCase__				=hf_hub_download(
					    repo_id='hf-internal-testing/spaghetti-video'			,	filename='eating_spaghetti_32_frames.npy'			,	repo_type='dataset'			)
					lowerCamelCase__				=np.load(__A			)
					return list(__A			)




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






						@cached_property
						def 		lowerCAmelCase   (					self)			->  Union[str, Any]:




											"""simple docstring"""





											return VivitImageProcessor() if is_vision_available() else None






						@slow
						def 		lowerCAmelCase   (					self)			->  str:




											"""simple docstring"""





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

											lowerCamelCase__				=self.default_image_processor
											lowerCamelCase__				=prepare_video()
											lowerCamelCase__				=image_processor(_SCREAMING_SNAKE_CASE    ,						return_tensors='pt').to(_SCREAMING_SNAKE_CASE)

											# forward pass
											with torch.no_grad():
																lowerCamelCase__				=model(**_SCREAMING_SNAKE_CASE)

											# verify the logits
											lowerCamelCase__				=torch.Size((1, 4_00))
											self.assertEqual(outputs.logits.shape    ,						_SCREAMING_SNAKE_CASE)

											# taken from original model
											lowerCamelCase__				=torch.tensor([-1.0543, 2.0764, -0.2104, 0.4439, -0.9658]).to(_SCREAMING_SNAKE_CASE)

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