





from manim import *





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__						:	List[Any] =				Rectangle(height=0.5					,  width=0.5)
          a__						:	str =				Rectangle(height=0.46					,  width=0.46).set_stroke(width=0)

          a__						:	Any =				Rectangle(height=0.25					,  width=0.25)

          a__						:	List[Any] =				[mem.copy() for i in range(6)]
          a__						:	Optional[Any] =				[mem.copy() for i in range(6)]
          a__						:	Tuple =				VGroup(*lowercase).arrange(lowercase					,  buff=0)
          a__						:	Dict =				VGroup(*lowercase).arrange(lowercase					,  buff=0)
          a__						:	List[Any] =				VGroup(lowercase					,  lowercase).arrange(lowercase					,  buff=0)
          a__						:	List[str] =				Text('CPU'					,  font_size=24)
          a__						:	Optional[Any] =				Group(lowercase					,  lowercase).arrange(lowercase					,  buff=0.5					,  aligned_edge=lowercase)
          cpu.move_to([-2.5, -0.5, 0])
          self.add(lowercase)

          a__						:	Dict =				[mem.copy() for i in range(4)]
          a__						:	Optional[Any] =				VGroup(*lowercase).arrange(lowercase					,  buff=0)
          a__						:	str =				Text('GPU'					,  font_size=24)
          a__						:	Any =				Group(lowercase					,  lowercase).arrange(lowercase					,  buff=0.5					,  aligned_edge=lowercase)
          gpu.move_to([-1, -1, 0])
          self.add(lowercase)

          a__						:	Any =				[mem.copy() for i in range(6)]
          a__						:	List[str] =				VGroup(*lowercase).arrange(lowercase					,  buff=0)

          a__						:	int =				Text('Model'					,  font_size=24)
          a__						:	List[Any] =				Group(lowercase					,  lowercase).arrange(lowercase					,  buff=0.5					,  aligned_edge=lowercase)
          model.move_to([3, -1.0, 0])
          self.add(lowercase)

          a__						:	Dict =				[]
          a__						:	str =				[]

          for i, rect in enumerate(lowercase):
                 a__						:	Tuple =				fill.copy().set_fill(lowercase					,  opacity=0.8)
                 target.move_to(lowercase)
                 model_arr.append(lowercase)

                 a__						:	int =				Rectangle(height=0.46					,  width=0.46).set_stroke(width=0.0).set_fill(lowercase					,  opacity=0.8)
                 cpu_target.move_to(cpu_left_col_base[i])
                 model_cpu_arr.append(lowercase)

          self.add(*lowercase					,  *lowercase)

          a__						:	Dict =				[meta_mem.copy() for i in range(6)]
          a__						:	List[Any] =				[meta_mem.copy() for i in range(6)]
          a__						:	Union[str, Any] =				VGroup(*lowercase).arrange(lowercase					,  buff=0)
          a__						:	Dict =				VGroup(*lowercase).arrange(lowercase					,  buff=0)
          a__						:	List[Any] =				VGroup(lowercase					,  lowercase).arrange(lowercase					,  buff=0)
          a__						:	Dict =				Text('Disk'					,  font_size=24)
          a__						:	Optional[int] =				Group(lowercase					,  lowercase).arrange(lowercase					,  buff=0.5					,  aligned_edge=lowercase)
          disk.move_to([-4, -1.25, 0])
          self.add(lowercase					,  lowercase)

          a__						:	List[str] =				Square(side_length=2.2)
          key.move_to([-5, 2, 0])

          a__						:	List[Any] =				MarkupText(
              F'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model'					,  font_size=18					,  )

          key_text.move_to([-5, 2.4, 0])

          self.add(lowercase					,  lowercase)

          a__						:	Dict =				MarkupText(
              F'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint'					,  font_size=18					,  )

          blue_text.next_to(lowercase					,  DOWN * 2.4					,  aligned_edge=key_text.get_left())
          self.add(lowercase)

          a__						:	Dict =				MarkupText(
              F'Now watch as an input is passed through the model\nand how the memory is utilized and handled.'					,  font_size=24					,  )
          step_a.move_to([2, 2, 0])

          self.play(Write(lowercase))

          a__						:	int =				Square(0.3)
          input.set_fill(lowercase					,  opacity=1.0)
          input.set_stroke(width=0.0)
          input.next_to(model_base[0]					,  lowercase					,  buff=0.5)

          self.play(Write(lowercase))

          input.generate_target()
          input.target.next_to(model_arr[0]					,  direction=lowercase					,  buff=0.02)
          self.play(MoveToTarget(lowercase))

          self.play(FadeOut(lowercase))

          a__						:	str =				Arrow(start=lowercase					,  end=lowercase					,  color=lowercase					,  buff=0.5)
          a.next_to(model_arr[0].get_left()					,  lowercase					,  buff=0.2)

          model_cpu_arr[0].generate_target()
          model_cpu_arr[0].target.move_to(gpu_rect[0])

          a__						:	Union[str, Any] =				MarkupText(
              F'As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.'					,  font_size=24					,  )
          step_a.move_to([2, 2, 0])

          self.play(Write(lowercase					,  run_time=3))

          a__						:	Union[str, Any] =				{'run_time': 1, 'fade_in': True, 'fade_out': True, 'buff': 0.02}

          self.play(
              Write(lowercase)					,  Circumscribe(model_arr[0]					,  color=lowercase					,  **lowercase)					,  Circumscribe(model_cpu_arr[0]					,  color=lowercase					,  **lowercase)					,  Circumscribe(gpu_rect[0]					,  color=lowercase					,  **lowercase)					,  )
          self.play(MoveToTarget(model_cpu_arr[0]))

          a__						:	List[Any] =				a.copy()
          for i in range(6):
                 a_c.next_to(model_arr[i].get_right() + 0.02					,  lowercase					,  buff=0.2)

                 input.generate_target()
                 input.target.move_to(model_arr[i].get_right() + 0.02)

                 a__						:	Any =				AnimationGroup(
                     FadeOut(lowercase					,  run_time=0.5)					,  MoveToTarget(lowercase					,  run_time=0.5)					,  FadeIn(lowercase					,  run_time=0.5)					,  lag_ratio=0.2)

                 self.play(lowercase)

                 model_cpu_arr[i].generate_target()
                 model_cpu_arr[i].target.move_to(cpu_left_col_base[i])

                 if i < 5:
                        model_cpu_arr[i + 1].generate_target()
                        model_cpu_arr[i + 1].target.move_to(gpu_rect[0])
                        if i >= 1:
                               a__						:	Tuple =				0.7

                        self.play(
                            Circumscribe(model_arr[i]					,  **lowercase)					,  Circumscribe(cpu_left_col_base[i]					,  **lowercase)					,  Circumscribe(cpu_left_col_base[i + 1]					,  color=lowercase					,  **lowercase)					,  Circumscribe(gpu_rect[0]					,  color=lowercase					,  **lowercase)					,  Circumscribe(model_arr[i + 1]					,  color=lowercase					,  **lowercase)					,  )
                        if i < 1:
                               self.play(
                                   MoveToTarget(model_cpu_arr[i])					,  MoveToTarget(model_cpu_arr[i + 1])					,  )
                        else:
                               self.play(
                                   MoveToTarget(model_cpu_arr[i]					,  run_time=0.7)					,  MoveToTarget(model_cpu_arr[i + 1]					,  run_time=0.7)					,  )
                 else:
                        model_cpu_arr[i].generate_target()
                        model_cpu_arr[i].target.move_to(cpu_left_col_base[-1])
                        input.generate_target()
                        input.target.next_to(model_arr[-1].get_right()					,  RIGHT + 0.02					,  buff=0.2)

                        self.play(
                            Circumscribe(model_arr[-1]					,  color=lowercase					,  **lowercase)					,  Circumscribe(cpu_left_col_base[-1]					,  color=lowercase					,  **lowercase)					,  Circumscribe(gpu_rect[0]					,  color=lowercase					,  **lowercase)					,  )

                        self.play(MoveToTarget(model_cpu_arr[i]))

                 a__						:	Optional[int] =				a_c
                 a__						:	str =				a_c.copy()

          input.generate_target()
          input.target.next_to(model_base[-1]					,  RIGHT + 0.02					,  buff=0.5)
          self.play(
              FadeOut(lowercase)					,  FadeOut(lowercase					,  run_time=0.5)					,  )

          a__						:	List[Any] =				MarkupText(F'Inference on a model too large for GPU memory\nis successfully completed.'					,  font_size=24)
          step_a.move_to([2, 2, 0])

          self.play(Write(lowercase					,  run_time=3)					,  MoveToTarget(lowercase))

          self.wait()









import inspect
import unittest

from transformers import ViTMSNConfig
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 ViTMSNForImageClassification, ViTMSNModel
    from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import ViTImageProcessor





class  A__    :




   """simple docstring"""



   def __init__(					self					,  lowercase					,  lowercase=13					,  lowercase=30					,  lowercase=2					,  lowercase=3					,  lowercase=True					,  lowercase=True					,  lowercase=32					,  lowercase=5					,  lowercase=4					,  lowercase=37					,  lowercase="gelu"					,  lowercase=0.1					,  lowercase=0.1					,  lowercase=10					,  lowercase=0.02					,  lowercase=None					,  )			->						Union[str, Any]:







          '''simple docstring'''

          a__						:	Optional[int] =				parent
          a__						:	List[str] =				batch_size
          a__						:	List[str] =				image_size
          a__						:	Dict =				patch_size
          a__						:	Optional[Any] =				num_channels
          a__						:	List[Any] =				is_training
          a__						:	str =				use_labels
          a__						:	Dict =				hidden_size
          a__						:	Tuple =				num_hidden_layers
          a__						:	Tuple =				num_attention_heads
          a__						:	Union[str, Any] =				intermediate_size
          a__						:	List[str] =				hidden_act
          a__						:	List[str] =				hidden_dropout_prob
          a__						:	Any =				attention_probs_dropout_prob
          a__						:	Dict =				type_sequence_label_size
          a__						:	Tuple =				initializer_range
          a__						:	Optional[int] =				scope

          # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
          a__						:	List[str] =				(image_size // patch_size) ** 2
          a__						:	Any =				num_patches + 1

   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          a__						:	Tuple =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          a__						:	Tuple =				None
          if self.use_labels:
                 a__						:	List[Any] =				ids_tensor([self.batch_size]					,  self.type_sequence_label_size)

          a__						:	List[str] =				self.get_config()

          return config, pixel_values, labels

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







          '''simple docstring'''

          return ViTMSNConfig(
              image_size=self.image_size					,  patch_size=self.patch_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					,  )

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						List[str]:







          '''simple docstring'''

          a__						:	int =				ViTMSNModel(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	int =				model(lowercase)
          self.parent.assertEqual(result.last_hidden_state.shape					,  (self.batch_size, self.seq_length, self.hidden_size))

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						Tuple:







          '''simple docstring'''

          a__						:	Optional[Any] =				self.type_sequence_label_size
          a__						:	List[str] =				ViTMSNForImageClassification(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	int =				model(lowercase					,  labels=lowercase)
          print('Pixel and labels shape: {pixel_values.shape}, {labels.shape}')
          print('Labels: {labels}')
          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.type_sequence_label_size))

          # test greyscale images
          a__						:	List[str] =				1
          a__						:	Optional[int] =				ViTMSNForImageClassification(lowercase)
          model.to(lowercase)
          model.eval()

          a__						:	Dict =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
          a__						:	Dict =				model(lowercase)
          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.type_sequence_label_size))

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__						:	List[Any] =				self.prepare_config_and_inputs()
          a__ ,							a__ ,							a__						:	Optional[Any] =				config_and_inputs
          a__						:	Dict =				{'pixel_values': pixel_values}
          return config, inputs_dict





@require_torch
class  A__    (							__UpperCAmelCase ,  __UpperCAmelCase ,  unittest.TestCase	):




   """simple docstring"""



   __A   :				Any         =  (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
   __A   :				Tuple         =  (
       {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification}
       if is_torch_available()
       else {}
   )

   __A   :				List[str]         =  False
   __A   :				Optional[Any]         =  False
   __A   :				Union[str, Any]         =  False
   __A   :				Any         =  False

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







          '''simple docstring'''

          a__						:	Optional[int] =				ViTMSNModelTester(self)
          a__						:	Union[str, Any] =				ConfigTester(self					,  config_class=lowercase					,  has_text_modality=lowercase					,  hidden_size=37)

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







          '''simple docstring'''

          self.config_tester.run_common_tests()

   @unittest.skip(reason='ViTMSN does not use inputs_embeds')
   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          pass

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__ ,							a__						:	Tuple =				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 a__						:	Union[str, Any] =				model_class(lowercase)
                 self.assertIsInstance(model.get_input_embeddings()					,  (nn.Module))
                 a__						:	str =				model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(lowercase					,  nn.Linear))

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__ ,							a__						:	Optional[int] =				self.model_tester.prepare_config_and_inputs_for_common()

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

                 a__						:	Optional[Any] =				['pixel_values']
                 self.assertListEqual(arg_names[:1]					,  lowercase)

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          a__						:	List[str] =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase)

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          a__						:	Any =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowercase)

   @slow
   def 							__lowercase		(					self)			->						Union[str, Any]:







          '''simple docstring'''

          for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a__						:	Tuple =				ViTMSNModel.from_pretrained(lowercase)
                 self.assertIsNotNone(lowercase)



def A_	(		)  ->		Dict:
       a__						:	List[str] =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
       return image





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




   """simple docstring"""



   @cached_property
   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          return ViTImageProcessor.from_pretrained('facebook/vit-msn-small') if is_vision_available() else None

   @slow
   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          torch.manual_seed(2)
          a__						:	List[str] =				ViTMSNForImageClassification.from_pretrained('facebook/vit-msn-small').to(lowercase)

          a__						:	Any =				self.default_image_processor
          a__						:	List[Any] =				prepare_img()
          a__						:	Optional[Any] =				image_processor(images=lowercase					,  return_tensors='pt').to(lowercase)

          # forward pass
          with torch.no_grad():
                 a__						:	Tuple =				model(**lowercase)

          # verify the logits
          a__						:	Union[str, Any] =				torch.Size((1, 1000))
          self.assertEqual(outputs.logits.shape					,  lowercase)

          a__						:	Any =				torch.tensor([-0.08_03, -0.44_54, -0.23_75]).to(lowercase)

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


