"""simple docstring"""




import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
     from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor
class 						__A							:






     def __init__(		self    ,					a__    ,					a__=13    ,					a__=32    ,					a__=3    ,					a__=4    ,					a__=[10, 20, 30, 40]    ,					a__=[2, 2, 3, 2]    ,					a__=True    ,					a__=True    ,					a__=37    ,					a__="gelu"    ,					a__=10    ,					a__=0.0_2    ,					a__=["stage2", "stage3", "stage4"]    ,					a__=[2, 3, 4]    ,					a__=None    ,					):
       _lowerCAmelCase						:	List[Any]        =					parent
       _lowerCAmelCase						:	str        =					batch_size
       _lowerCAmelCase						:	Tuple        =					image_size
       _lowerCAmelCase						:	Dict        =					num_channels
       _lowerCAmelCase						:	Optional[Any]        =					num_stages
       _lowerCAmelCase						:	int        =					hidden_sizes
       _lowerCAmelCase						:	Optional[Any]        =					depths
       _lowerCAmelCase						:	Any        =					is_training
       _lowerCAmelCase						:	List[Any]        =					use_labels
       _lowerCAmelCase						:	Tuple        =					intermediate_size
       _lowerCAmelCase						:	Optional[Any]        =					hidden_act
       _lowerCAmelCase						:	Optional[Any]        =					num_labels
       _lowerCAmelCase						:	Optional[int]        =					initializer_range
       _lowerCAmelCase						:	Optional[int]        =					out_features
       _lowerCAmelCase						:	Tuple        =					out_indices
       _lowerCAmelCase						:	str        =					scope






     def    __A  (		self  ):
       _lowerCAmelCase						:	str        =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

       _lowerCAmelCase						:	Optional[int]        =					None
       if self.use_labels:
         _lowerCAmelCase						:	str        =					ids_tensor([self.batch_size]    ,					self.num_labels  )

       _lowerCAmelCase						:	Tuple        =					self.get_config()

       return config, pixel_values, labels






     def    __A  (		self  ):
       return ConvNextVaConfig(
           num_channels=self.num_channels    ,					hidden_sizes=self.hidden_sizes    ,					depths=self.depths    ,					num_stages=self.num_stages    ,					hidden_act=self.hidden_act    ,					is_decoder=a__    ,					initializer_range=self.initializer_range    ,					out_features=self.out_features    ,					out_indices=self.out_indices    ,					num_labels=self.num_labels    ,					)






     def    __A  (		self    ,					a__    ,					a__    ,					a__  ):
       _lowerCAmelCase						:	int        =					ConvNextVaModel(config=a__  )
       model.to(a__  )
       model.eval()
       _lowerCAmelCase						:	str        =					model(a__  )
       # expected last hidden states: B, C, H // 32, W // 32
       self.parent.assertEqual(
           result.last_hidden_state.shape    ,					(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)    ,					)






     def    __A  (		self    ,					a__    ,					a__    ,					a__  ):
       _lowerCAmelCase						:	Optional[int]        =					ConvNextVaForImageClassification(a__  )
       model.to(a__  )
       model.eval()
       _lowerCAmelCase						:	Optional[int]        =					model(a__    ,					labels=a__  )
       self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.num_labels)  )






     def    __A  (		self    ,					a__    ,					a__    ,					a__  ):
       _lowerCAmelCase						:	Any        =					ConvNextVaBackbone(config=a__  )
       model.to(a__  )
       model.eval()
       _lowerCAmelCase						:	Tuple        =					model(a__  )

       # verify hidden states
       self.parent.assertEqual(len(result.feature_maps  )    ,					len(config.out_features  )  )
       self.parent.assertListEqual(list(result.feature_maps[0].shape  )    ,					[self.batch_size, self.hidden_sizes[1], 4, 4]  )

       # verify channels
       self.parent.assertEqual(len(model.channels  )    ,					len(config.out_features  )  )
       self.parent.assertListEqual(model.channels    ,					config.hidden_sizes[1:]  )

       # verify backbone works with out_features=None
       _lowerCAmelCase						:	List[str]        =					None
       _lowerCAmelCase						:	int        =					ConvNextVaBackbone(config=a__  )
       model.to(a__  )
       model.eval()
       _lowerCAmelCase						:	Optional[int]        =					model(a__  )

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps  )    ,					1  )
       self.parent.assertListEqual(list(result.feature_maps[0].shape  )    ,					[self.batch_size, self.hidden_sizes[-1], 1, 1]  )

       # verify channels
       self.parent.assertEqual(len(model.channels  )    ,					1  )
       self.parent.assertListEqual(model.channels    ,					[config.hidden_sizes[-1]]  )






     def    __A  (		self  ):
       _lowerCAmelCase						:	Optional[Any]        =					self.prepare_config_and_inputs()
       _lowerCAmelCase      ,     _lowerCAmelCase      ,     _lowerCAmelCase						:	Union[str, Any]        =					config_and_inputs
       _lowerCAmelCase						:	Any        =					{"""pixel_values""": pixel_values}
       return config, inputs_dict






     def    __A  (		self  ):
       _lowerCAmelCase						:	int        =					self.prepare_config_and_inputs()
       _lowerCAmelCase      ,     _lowerCAmelCase      ,     _lowerCAmelCase						:	Optional[Any]        =					config_and_inputs
       _lowerCAmelCase						:	int        =					{"""pixel_values""": pixel_values, """labels""": labels}
       return config, inputs_dict







@require_torch
class 						__A							(			SCREAMING_SNAKE_CASE_   ,     SCREAMING_SNAKE_CASE_   ,     unittest.TestCase		):
     _UpperCamelCase							:      Optional[int]		 =		(
         (
             ConvNextVaModel,
             ConvNextVaForImageClassification,
             ConvNextVaBackbone,
         )
         if is_torch_available()
         else ()
     )
     _UpperCamelCase							:      Optional[Any]		 =		(
         {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
         if is_torch_available()
         else {}
     )

     _UpperCamelCase							:      Optional[int]		 =		False
     _UpperCamelCase							:      Optional[Any]		 =		False
     _UpperCamelCase							:      Optional[int]		 =		False
     _UpperCamelCase							:      Union[str, Any]		 =		False
     _UpperCamelCase							:      List[Any]		 =		False






     def    __A  (		self  ):
       _lowerCAmelCase						:	Optional[Any]        =					ConvNextVaModelTester(self  )
       _lowerCAmelCase						:	List[Any]        =					ConfigTester(self    ,					config_class=a__    ,					has_text_modality=a__    ,					hidden_size=37  )






     def    __A  (		self  ):
       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()






     def    __A  (		self  ):
       return






     @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds"""  )
     def    __A  (		self  ):
       pass






     @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings"""  )
     def    __A  (		self  ):
       pass






     @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking"""  )
     def    __A  (		self  ):
       pass






     def    __A  (		self  ):
       if not self.model_tester.is_training:
         return

       for model_class in self.all_model_classes:
         _lowerCAmelCase      ,     _lowerCAmelCase						:	int        =					self.model_tester.prepare_config_and_inputs_with_labels()
         _lowerCAmelCase						:	Tuple        =					True

         if model_class.__name__ in [
             *get_values(a__  ),
             *get_values(a__  ),
         ]:
           continue

         _lowerCAmelCase						:	Optional[Any]        =					model_class(a__  )
         model.to(a__  )
         model.train()
         _lowerCAmelCase						:	str        =					self._prepare_for_class(a__    ,					a__    ,					return_labels=a__  )
         _lowerCAmelCase						:	Optional[int]        =					model(**a__  ).loss
         loss.backward()






     def    __A  (		self  ):
       if not self.model_tester.is_training:
         return

       for model_class in self.all_model_classes:
         _lowerCAmelCase      ,     _lowerCAmelCase						:	Optional[Any]        =					self.model_tester.prepare_config_and_inputs_with_labels()
         _lowerCAmelCase						:	int        =					False
         _lowerCAmelCase						:	List[Any]        =					True

         if (
             model_class.__name__
             in [*get_values(a__  ), *get_values(a__  )]
             or not model_class.supports_gradient_checkpointing
         ):
           continue

         _lowerCAmelCase						:	Tuple        =					model_class(a__  )
         model.to(a__  )
         model.gradient_checkpointing_enable()
         model.train()
         _lowerCAmelCase						:	Dict        =					self._prepare_for_class(a__    ,					a__    ,					return_labels=a__  )
         _lowerCAmelCase						:	Optional[int]        =					model(**a__  ).loss
         loss.backward()






     def    __A  (		self  ):
       _lowerCAmelCase      ,     _lowerCAmelCase						:	Optional[Any]        =					self.model_tester.prepare_config_and_inputs_for_common()

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

         _lowerCAmelCase						:	Dict        =					["""pixel_values"""]
         self.assertListEqual(arg_names[:1]    ,					a__  )






     def    __A  (		self  ):
       _lowerCAmelCase						:	int        =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*a__  )






     def    __A  (		self  ):
       def check_hidden_states_output(a__    ,					a__    ,					a__  ):
         _lowerCAmelCase						:	Tuple        =					model_class(a__  )
         model.to(a__  )
         model.eval()

         with torch.no_grad():
           _lowerCAmelCase						:	Tuple        =					model(**self._prepare_for_class(a__    ,					a__  )  )

         _lowerCAmelCase						:	List[Any]        =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         _lowerCAmelCase						:	Tuple        =					self.model_tester.num_stages
         self.assertEqual(len(a__  )    ,					expected_num_stages + 1  )

         # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width)
         self.assertListEqual(
             list(hidden_states[0].shape[-2:]  )    ,					[self.model_tester.image_size // 4, self.model_tester.image_size // 4]    ,					)

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

       for model_class in self.all_model_classes:
         _lowerCAmelCase						:	int        =					True
         check_hidden_states_output(a__    ,					a__    ,					a__  )

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         _lowerCAmelCase						:	List[str]        =					True

         check_hidden_states_output(a__    ,					a__    ,					a__  )






     def    __A  (		self  ):
       _lowerCAmelCase						:	Tuple        =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*a__  )






     @slow
     def    __A  (		self  ):
       for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _lowerCAmelCase						:	Dict        =					ConvNextVaModel.from_pretrained(a__  )
         self.assertIsNotNone(a__  )







def 							SCREAMING_SNAKE_CASE					(      )	->				Any:
  _lowerCAmelCase						:	List[Any]        =					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
  return image






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






     @cached_property
     def    __A  (		self  ):
       return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224"""  ) if is_vision_available() else None






     @slow
     def    __A  (		self  ):
       _lowerCAmelCase						:	str        =					ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224"""  ).to(a__  )

       _lowerCAmelCase						:	int        =					self.default_image_processor
       _lowerCAmelCase						:	Dict        =					prepare_img()
       _lowerCAmelCase						:	Dict        =					preprocessor(images=a__    ,					return_tensors="""pt"""  ).to(a__  )

       # forward pass
       with torch.no_grad():
         _lowerCAmelCase						:	int        =					model(**a__  )

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

       _lowerCAmelCase						:	int        =					torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6]  ).to(a__  )
       self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,					a__    ,					atol=1e-4  )  )





"""simple docstring"""




from manim import *
class 						__A							(			SCREAMING_SNAKE_CASE_		):






     def    __A  (		self  ):
       _lowerCAmelCase						:	Any        =					Rectangle(height=0.5    ,					width=0.5  )
       _lowerCAmelCase						:	List[Any]        =					Rectangle(height=0.4_6    ,					width=0.4_6  ).set_stroke(width=0  )

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

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

       _lowerCAmelCase						:	Optional[int]        =					[mem.copy() for i in range(6  )]
       _lowerCAmelCase						:	Any        =					VGroup(*a__  ).arrange(a__    ,					buff=0  )

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

       _lowerCAmelCase						:	Tuple        =					[]
       for i, rect in enumerate(a__  ):
         rect.set_stroke(a__  )
         # target = fill.copy().set_fill(YELLOW, opacity=0.7)
         # target.move_to(rect)
         # self.add(target)

         _lowerCAmelCase						:	List[str]        =					Rectangle(height=0.4_6 / 4    ,					width=0.4_6 / 3  ).set_stroke(width=0.0  ).set_fill(a__    ,					opacity=0.7  )

         if i == 0:
           cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT  )    ,					buff=0.0_2    ,					direction=a__  )
           cpu_target.set_x(cpu_target.get_x() + 0.1  )
         elif i == 3:
           cpu_target.next_to(cpu_targs[0]    ,					direction=a__    ,					buff=0.0  )
         else:
           cpu_target.next_to(cpu_targs[i - 1]    ,					direction=a__    ,					buff=0.0  )
         self.add(a__  )
         cpu_targs.append(a__  )

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

       _lowerCAmelCase						:	int        =					Text("""Loaded Checkpoint"""    ,					font_size=24  )
       _lowerCAmelCase						:	Optional[int]        =					Group(a__    ,					a__  ).arrange(a__    ,					aligned_edge=a__    ,					buff=0.4  )
       checkpoint.move_to([3, 0.5, 0]  )

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

       _lowerCAmelCase						:	List[str]        =					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(a__    ,					a__  )

       _lowerCAmelCase						:	int        =					MarkupText(
           F"<span fgcolor='{BLUE}'>●</span> Checkpoint"    ,					font_size=18    ,					)

       blue_text.next_to(a__    ,					DOWN * 2.4    ,					aligned_edge=key_text.get_left()  )

       _lowerCAmelCase						:	List[Any]        =					MarkupText(
           F"Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>."    ,					font_size=24    ,					)
       step_a.move_to([2, 2, 0]  )
       self.play(Write(a__  )    ,					Write(a__  )  )

       self.play(Write(a__    ,					run_time=1  )    ,					Create(a__    ,					run_time=1  )  )

       _lowerCAmelCase						:	int        =					[]
       _lowerCAmelCase						:	List[Any]        =					[]
       for i, rect in enumerate(a__  ):
         _lowerCAmelCase						:	Tuple        =					fill.copy().set_fill(a__    ,					opacity=0.7  )
         target.move_to(a__  )
         first_animations.append(GrowFromCenter(a__    ,					run_time=1  )  )

         _lowerCAmelCase						:	Optional[Any]        =					target.copy()
         cpu_target.generate_target()
         if i < 5:
           cpu_target.target.move_to(cpu_left_col_base[i + 1]  )
         else:
           cpu_target.target.move_to(cpu_right_col_base[i - 5]  )
         second_animations.append(MoveToTarget(a__    ,					run_time=1.5  )  )

       self.play(*a__  )
       self.play(*a__  )
       self.wait()




