





'''simple docstring'''







import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
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,
					    TimesformerForVideoClassification,
					    TimesformerModel,
					)
					from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from transformers import VideoMAEImageProcessor
class 				__SCREAMING_SNAKE_CASE  :






				"""simple docstring"""







				def __init__(  self     :					List[str]					,				__a     :					List[Any]					,				__a     :					str=13					,				__a     :					Dict=10					,				__a     :					Tuple=3					,				__a     :					Dict=2					,				__a     :					Any=2					,				__a     :					Union[str, Any]=True					,				__a     :					str=True					,				__a     :					Optional[int]=32					,				__a     :					List[str]=5					,				__a     :					int=4					,				__a     :					Any=37					,				__a     :					Optional[Any]="gelu"					,				__a     :					Optional[int]=0.1					,				__a     :					List[str]=0.1					,				__a     :					Tuple=10					,				__a     :					Union[str, Any]=0.02					,				__a     :					Union[str, Any]="divided_space_time"					,				__a     :					Dict=None					,				):
								_a								= parent
								_a								= batch_size
								_a								= image_size
								_a								= num_channels
								_a								= patch_size
								_a								= num_frames
								_a								= is_training
								_a								= use_labels
								_a								= hidden_size
								_a								= num_hidden_layers
								_a								= num_attention_heads
								_a								= intermediate_size
								_a								= hidden_act
								_a								= hidden_dropout_prob
								_a								= attention_probs_dropout_prob
								_a								= attention_type
								_a								= initializer_range
								_a								= scope
								_a								= num_labels

								# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
								_a								= (image_size // patch_size) ** 2
								_a								= (num_frames) * self.num_patches_per_frame + 1




				def   UpperCamelCase__   (  self     :					Union[str, Any]					):
								_a								= floats_tensor(
								    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]					)

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

								_a								= self.get_config()

								return config, pixel_values, labels




				def   UpperCamelCase__   (  self     :					int					):
								_a								= TimesformerConfig(
								    image_size=self.image_size					,				patch_size=self.patch_size					,				num_channels=self.num_channels					,				num_frames=self.num_frames					,				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					,				attention_type=self.attention_type					,				)
								_a								= self.num_labels
								return config




				def   UpperCamelCase__   (  self     :					List[Any]					,				__a     :					str					,				__a     :					Union[str, Any]					,				__a     :					List[str]					):
								_a								= TimesformerModel(config=__a					)
								model.to(__a					)
								model.eval()
								_a								= model(__a					)
								self.parent.assertEqual(result.last_hidden_state.shape					,				(self.batch_size, self.seq_length, self.hidden_size)					)




				def   UpperCamelCase__   (  self     :					Any					,				__a     :					Union[str, Any]					,				__a     :					str					,				__a     :					List[Any]					):
								_a								= TimesformerForVideoClassification(__a					)
								model.to(__a					)
								model.eval()

								_a								= model(__a					)

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




				def   UpperCamelCase__   (  self     :					Any					):
								_a								= self.prepare_config_and_inputs()
								_a	,					_a	,					_a								= config_and_inputs
								_a								= {"pixel_values": pixel_values}
								return config, inputs_dict


@require_torch
class 				__SCREAMING_SNAKE_CASE  (lowerCamelCase_       ,							lowerCamelCase_       ,							unittest.TestCase      ):






				"""simple docstring"""







				__a            =(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
				__a            =(
				    {'feature-extraction': TimesformerModel, 'video-classification': TimesformerForVideoClassification}
				    if is_torch_available()
				    else {}
				)

				__a            =False
				__a            =False
				__a            =False
				__a            =False




				def   UpperCamelCase__   (  self     :					Dict					):
								_a								= TimesformerModelTester(self					)
								_a								= ConfigTester(
								    self					,				config_class=__a					,				has_text_modality=__a					,				hidden_size=37					)




				def   UpperCamelCase__   (  self     :					int					,				__a     :					List[Any]					,				__a     :					List[Any]					,				__a     :					Any=False					):
								_a								= copy.deepcopy(__a					)

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

								return inputs_dict




				def   UpperCamelCase__   (  self     :					int					):
								self.config_tester.run_common_tests()




				@unittest.skip(reason="TimeSformer does not use inputs_embeds"					)
				def   UpperCamelCase__   (  self     :					List[Any]					):
								pass




				def   UpperCamelCase__   (  self     :					Optional[int]					):
								_a	,					_a								= self.model_tester.prepare_config_and_inputs_for_common()

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




				def   UpperCamelCase__   (  self     :					Dict					):
								_a	,					_a								= self.model_tester.prepare_config_and_inputs_for_common()

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

												_a								= ["pixel_values"]
												self.assertListEqual(arg_names[:1]					,				__a					)




				def   UpperCamelCase__   (  self     :					Optional[int]					):
								_a								= self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__a					)




				def   UpperCamelCase__   (  self     :					List[str]					):
								_a								= self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_video_classification(*__a					)




				@slow
				def   UpperCamelCase__   (  self     :					Tuple					):
								for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												_a								= TimesformerModel.from_pretrained(__a					)
												self.assertIsNotNone(__a					)




				def   UpperCamelCase__   (  self     :					Optional[Any]					):
								if not self.has_attentions:
												pass

								else:
												_a	,					_a								= self.model_tester.prepare_config_and_inputs_for_common()
												_a								= True

												for model_class in self.all_model_classes:
																_a								= self.model_tester.seq_length
																_a								= self.model_tester.num_frames

																_a								= True
																_a								= False
																_a								= True
																_a								= model_class(__a					)
																model.to(__a					)
																model.eval()
																with torch.no_grad():
																				_a								= model(**self._prepare_for_class(__a					,				__a					)					)
																_a								= 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"]
																_a								= True
																_a								= model_class(__a					)
																model.to(__a					)
																model.eval()
																with torch.no_grad():
																				_a								= model(**self._prepare_for_class(__a					,				__a					)					)
																_a								= outputs.attentions
																self.assertEqual(len(__a					)					,				self.model_tester.num_hidden_layers					)

																# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
																self.assertListEqual(
																    list(attentions[0].shape[-3:]					)					,				[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]					,				)
																_a								= len(__a					)

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

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

																_a								= outputs.attentions

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

																# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
																self.assertListEqual(
																    list(self_attentions[0].shape[-3:]					)					,				[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]					,				)




				def   UpperCamelCase__   (  self     :					str					):
								def check_hidden_states_output(__a     :					Union[str, Any]					,				__a     :					Optional[Any]					,				__a     :					Any					):
												_a								= model_class(__a					)
												model.to(__a					)
												model.eval()

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

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

												_a								= self.model_tester.seq_length

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

								_a	,					_a								= self.model_tester.prepare_config_and_inputs_for_common()

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

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

												check_hidden_states_output(__a					,				__a					,				__a					)






def  _lowerCamelCase				( )	->	int:
				_a								= hf_hub_download(
				    repo_id="hf-internal-testing/spaghetti-video"    ,							filename="eating_spaghetti.npy"    ,							repo_type="dataset"						)
				_a								= np.load(lowercase						)
				return list(lowercase						)



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






				"""simple docstring"""







				@cached_property
				def   UpperCamelCase__   (  self     :					List[str]					):
								# 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     :					str					):
								_a								= TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400"					).to(
								    __a					)

								_a								= self.default_image_processor
								_a								= prepare_video()
								_a								= image_processor(video[:8]					,				return_tensors="pt"					).to(__a					)

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

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

								_a								= torch.tensor([-0.3016, -0.7713, -0.4205]					).to(__a					)

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







from __future__ import annotations

from functools import lru_cache
from math import ceil

__lowerCamelCase       :     str   =     100

__lowerCamelCase       :     Any   =     set(range(3, NUM_PRIMES, 2))
primes.add(2)
__lowerCamelCase       :     int

for prime in range(3, ceil(NUM_PRIMES**0.5), 2):
    if prime not in primes:
        continue
    primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime)))



@lru_cache(maxsize=100     )
def 		A_				(     _lowerCAmelCase     )						-> set[int]:
 if number_to_partition < 0:
  return set()
 elif number_to_partition == 0:
  return {1}

 UpperCamelCase	:					set[int]       	=   set()
 UpperCamelCase	:					int
 UpperCamelCase	:					int

 for prime in primes:
  if prime > number_to_partition:
   continue
  for sub in partition(number_to_partition - prime     ):
   ret.add(sub * prime     )

 return ret



def 		A_				(     _lowerCAmelCase = 5000     )						-> int | None:
 for number_to_partition in range(1							,   _lowerCAmelCase     ):
  if len(partition(_lowerCAmelCase     )     ) > number_unique_partitions:
   return number_to_partition
 return None


if __name__ == "__main__":
    print(f"""{solution() = }""")
