



'''simple docstring'''


import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

   if is_vision_available():
      from transformers import MaskaFormerImageProcessor

if is_vision_available():
   from PIL import Image

class 					SCREAMING_SNAKE_CASE					:






    """simple docstring"""





    def __init__(    self :   Optional[int]    ,		UpperCamelCase__ :   Optional[int]    ,		UpperCamelCase__ :   Optional[Any]=2    ,		UpperCamelCase__ :   Dict=True    ,		UpperCamelCase__ :   List[Any]=False    ,		UpperCamelCase__ :   Union[str, Any]=1_0    ,		UpperCamelCase__ :   int=3    ,		UpperCamelCase__ :   Any=3_2 * 8    ,		UpperCamelCase__ :   Any=3_2 * 8    ,		UpperCamelCase__ :   Optional[Any]=4    ,		UpperCamelCase__ :   List[Any]=6_4    ,		):


       """simple docstring"""







       UpperCamelCase      							=    parent
       UpperCamelCase      							=    batch_size
       UpperCamelCase      							=    is_training
       UpperCamelCase      							=    use_auxiliary_loss
       UpperCamelCase      							=    num_queries
       UpperCamelCase      							=    num_channels
       UpperCamelCase      							=    min_size
       UpperCamelCase      							=    max_size
       UpperCamelCase      							=    num_labels
       UpperCamelCase      							=    hidden_dim
       UpperCamelCase      							=    hidden_dim






    def 					A			(    self :   List[str]					):


       """simple docstring"""







       UpperCamelCase      							=    floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]					).to(
           UpperCamelCase__					)

       UpperCamelCase      							=    torch.ones([self.batch_size, self.min_size, self.max_size]    ,		device=UpperCamelCase__					)

       UpperCamelCase      							=    (
           torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]    ,		device=UpperCamelCase__					) > 0.5
       ).float()
       UpperCamelCase      							=    (torch.rand((self.batch_size, self.num_labels)    ,		device=UpperCamelCase__					) > 0.5).long()

       UpperCamelCase      							=    self.get_config()
       return config, pixel_values, pixel_mask, mask_labels, class_labels






    def 					A			(    self :   int					):


       """simple docstring"""







       UpperCamelCase      							=    MaskaFormerConfig(
           hidden_size=self.hidden_dim    ,		)
       UpperCamelCase      							=    self.num_queries
       UpperCamelCase      							=    self.num_labels

       UpperCamelCase      							=    [1, 1, 1, 1]
       UpperCamelCase      							=    self.num_channels

       UpperCamelCase      							=    6_4
       UpperCamelCase      							=    1_2_8
       UpperCamelCase      							=    self.hidden_dim
       UpperCamelCase      							=    self.hidden_dim
       UpperCamelCase      							=    self.hidden_dim
       return config






    def 					A			(    self :   List[Any]					):


       """simple docstring"""







       UpperCamelCase							, UpperCamelCase							, UpperCamelCase							, UpperCamelCase							, UpperCamelCase      							=    self.prepare_config_and_inputs()
       UpperCamelCase      							=    {'pixel_values': pixel_values, 'pixel_mask': pixel_mask}
       return config, inputs_dict






    def 					A			(    self :   Tuple    ,		UpperCamelCase__ :   Union[str, Any]    ,		UpperCamelCase__ :   Dict					):


       """simple docstring"""







       UpperCamelCase      							=    output.encoder_hidden_states
       UpperCamelCase      							=    output.pixel_decoder_hidden_states
       UpperCamelCase      							=    output.transformer_decoder_hidden_states

       self.parent.assertTrue(len(UpperCamelCase__					)    ,		len(config.backbone_config.depths					)					)
       self.parent.assertTrue(len(UpperCamelCase__					)    ,		len(config.backbone_config.depths					)					)
       self.parent.assertTrue(len(UpperCamelCase__					)    ,		config.decoder_layers					)






    def 					A			(    self :   Dict    ,		UpperCamelCase__ :   List[str]    ,		UpperCamelCase__ :   Union[str, Any]    ,		UpperCamelCase__ :   int    ,		UpperCamelCase__ :   Any=False					):


       """simple docstring"""







       with torch.no_grad():
          UpperCamelCase      							=    MaskaFormerModel(config=UpperCamelCase__					)
          model.to(UpperCamelCase__					)
          model.eval()

          UpperCamelCase      							=    model(pixel_values=UpperCamelCase__    ,		pixel_mask=UpperCamelCase__					)
          UpperCamelCase      							=    model(UpperCamelCase__    ,		output_hidden_states=UpperCamelCase__					)

       self.parent.assertEqual(
           output.transformer_decoder_last_hidden_state.shape    ,		(self.batch_size, self.num_queries, self.hidden_dim)    ,		)
       # let's ensure the other two hidden state exists
       self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None					)
       self.parent.assertTrue(output.encoder_last_hidden_state is not None					)

       if output_hidden_states:
          self.check_output_hidden_state(UpperCamelCase__    ,		UpperCamelCase__					)






    def 					A			(    self :   Optional[Any]    ,		UpperCamelCase__ :   Any    ,		UpperCamelCase__ :   Tuple    ,		UpperCamelCase__ :   str    ,		UpperCamelCase__ :   str    ,		UpperCamelCase__ :   Dict					):


       """simple docstring"""







       UpperCamelCase      							=    MaskaFormerForUniversalSegmentation(config=UpperCamelCase__					)
       model.to(UpperCamelCase__					)
       model.eval()

       def comm_check_on_output(UpperCamelCase__ :   Dict					):
          # let's still check that all the required stuff is there
          self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None					)
          self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None					)
          self.parent.assertTrue(result.encoder_last_hidden_state is not None					)
          # okay, now we need to check the logits shape
          # due to the encoder compression, masks have a //4 spatial size
          self.parent.assertEqual(
              result.masks_queries_logits.shape    ,		(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)    ,		)
          # + 1 for null class
          self.parent.assertEqual(
              result.class_queries_logits.shape    ,		(self.batch_size, self.num_queries, self.num_labels + 1)					)

       with torch.no_grad():
          UpperCamelCase      							=    model(pixel_values=UpperCamelCase__    ,		pixel_mask=UpperCamelCase__					)
          UpperCamelCase      							=    model(UpperCamelCase__					)

          comm_check_on_output(UpperCamelCase__					)

          UpperCamelCase      							=    model(
              pixel_values=UpperCamelCase__    ,		pixel_mask=UpperCamelCase__    ,		mask_labels=UpperCamelCase__    ,		class_labels=UpperCamelCase__					)

       comm_check_on_output(UpperCamelCase__					)

       self.parent.assertTrue(result.loss is not None					)
       self.parent.assertEqual(result.loss.shape    ,		torch.Size([1]					)					)

@require_torch
class 					SCREAMING_SNAKE_CASE					(    __lowercase  ,		__lowercase  ,		unittest.TestCase						):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE          =    (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
    _SCREAMING_SNAKE_CASE          =    {"feature-extraction": MaskaFormerModel} if is_torch_available() else {}

    _SCREAMING_SNAKE_CASE          =    False
    _SCREAMING_SNAKE_CASE          =    False
    _SCREAMING_SNAKE_CASE          =    False
    _SCREAMING_SNAKE_CASE          =    False






    def 					A			(    self :   Tuple					):


       """simple docstring"""







       UpperCamelCase      							=    MaskaFormerModelTester(self					)
       UpperCamelCase      							=    ConfigTester(self    ,		config_class=UpperCamelCase__    ,		has_text_modality=UpperCamelCase__					)






    def 					A			(    self :   str					):


       """simple docstring"""







       self.config_tester.run_common_tests()






    def 					A			(    self :   Optional[Any]					):


       """simple docstring"""







       UpperCamelCase							, UpperCamelCase      							=    self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskaformer_model(UpperCamelCase__    ,		**UpperCamelCase__    ,		output_hidden_states=UpperCamelCase__					)






    def 					A			(    self :   Any					):


       """simple docstring"""







       UpperCamelCase      							=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*UpperCamelCase__					)






    @unittest.skip(reason='Mask2Former does not use inputs_embeds'					)
    def 					A			(    self :   Optional[Any]					):


       """simple docstring"""







       pass






    @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method'					)
    def 					A			(    self :   Optional[int]					):


       """simple docstring"""







       pass






    @unittest.skip(reason='Mask2Former is not a generative model'					)
    def 					A			(    self :   Dict					):


       """simple docstring"""







       pass






    @unittest.skip(reason='Mask2Former does not use token embeddings'					)
    def 					A			(    self :   Tuple					):


       """simple docstring"""







       pass






    @require_torch_multi_gpu
    @unittest.skip(
        reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'					)
    def 					A			(    self :   int					):


       """simple docstring"""







       pass






    @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'					)
    def 					A			(    self :   Optional[Any]					):


       """simple docstring"""







       pass






    def 					A			(    self :   int					):


       """simple docstring"""







       UpperCamelCase							, UpperCamelCase      							=    self.model_tester.prepare_config_and_inputs_for_common()

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

          UpperCamelCase      							=    ['pixel_values']
          self.assertListEqual(arg_names[:1]    ,		UpperCamelCase__					)






    @slow
    def 					A			(    self :   Tuple					):


       """simple docstring"""







       for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
          UpperCamelCase      							=    MaskaFormerModel.from_pretrained(UpperCamelCase__					)
          self.assertIsNotNone(UpperCamelCase__					)






    def 					A			(    self :   str					):


       """simple docstring"""







       UpperCamelCase      							=    (self.model_tester.min_size,) * 2
       UpperCamelCase      							=    {
           'pixel_values': torch.randn((2, 3, *size)    ,		device=UpperCamelCase__					),
           'mask_labels': torch.randn((2, 1_0, *size)    ,		device=UpperCamelCase__					),
           'class_labels': torch.zeros(2    ,		1_0    ,		device=UpperCamelCase__					).long(),
       }
       UpperCamelCase      							=    self.model_tester.get_config()

       UpperCamelCase      							=    MaskaFormerForUniversalSegmentation(UpperCamelCase__					).to(UpperCamelCase__					)
       UpperCamelCase      							=    model(**UpperCamelCase__					)
       self.assertTrue(outputs.loss is not None					)






    def 					A			(    self :   List[Any]					):


       """simple docstring"""







       UpperCamelCase							, UpperCamelCase      							=    self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskaformer_model(UpperCamelCase__    ,		**UpperCamelCase__    ,		output_hidden_states=UpperCamelCase__					)






    def 					A			(    self :   int					):


       """simple docstring"""







       UpperCamelCase							, UpperCamelCase      							=    self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          UpperCamelCase      							=    model_class(UpperCamelCase__					).to(UpperCamelCase__					)
          UpperCamelCase      							=    model(**UpperCamelCase__    ,		output_attentions=UpperCamelCase__					)
          self.assertTrue(outputs.attentions is not None					)






    def 					A			(    self :   List[str]					):


       """simple docstring"""







       if not self.model_tester.is_training:
          return

       UpperCamelCase      							=    self.all_model_classes[1]
       UpperCamelCase							, UpperCamelCase							, UpperCamelCase							, UpperCamelCase							, UpperCamelCase      							=    self.model_tester.prepare_config_and_inputs()

       UpperCamelCase      							=    model_class(UpperCamelCase__					)
       model.to(UpperCamelCase__					)
       model.train()

       UpperCamelCase      							=    model(UpperCamelCase__    ,		mask_labels=UpperCamelCase__    ,		class_labels=UpperCamelCase__					).loss
       loss.backward()






    def 					A			(    self :   Any					):


       """simple docstring"""







       UpperCamelCase      							=    self.all_model_classes[1]
       UpperCamelCase							, UpperCamelCase							, UpperCamelCase							, UpperCamelCase							, UpperCamelCase      							=    self.model_tester.prepare_config_and_inputs()
       UpperCamelCase      							=    True
       UpperCamelCase      							=    True

       UpperCamelCase      							=    model_class(UpperCamelCase__					).to(UpperCamelCase__					)
       model.train()

       UpperCamelCase      							=    model(UpperCamelCase__    ,		mask_labels=UpperCamelCase__    ,		class_labels=UpperCamelCase__					)

       UpperCamelCase      							=    outputs.encoder_hidden_states[0]
       encoder_hidden_states.retain_grad()

       UpperCamelCase      							=    outputs.pixel_decoder_hidden_states[0]
       pixel_decoder_hidden_states.retain_grad()

       UpperCamelCase      							=    outputs.transformer_decoder_hidden_states[0]
       transformer_decoder_hidden_states.retain_grad()

       UpperCamelCase      							=    outputs.attentions[0]
       attentions.retain_grad()

       outputs.loss.backward(retain_graph=UpperCamelCase__					)

       self.assertIsNotNone(encoder_hidden_states.grad					)
       self.assertIsNotNone(pixel_decoder_hidden_states.grad					)
       self.assertIsNotNone(transformer_decoder_hidden_states.grad					)
       self.assertIsNotNone(attentions.grad					)

_lowerCamelCase      :			Dict       =      1e-4







def 							__lowerCamelCase							(  )			->      str:






   """simple docstring"""
   UpperCamelCase      							=    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
   return image

@require_vision
@slow
class 					SCREAMING_SNAKE_CASE					(    unittest.TestCase						):






    """simple docstring"""





    @cached_property
    def 					A			(    self :   Union[str, Any]					):


       """simple docstring"""







       return "facebook/mask2former-swin-small-coco-instance"






    @cached_property
    def 					A			(    self :   Optional[Any]					):


       """simple docstring"""







       return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints					) if is_vision_available() else None






    def 					A			(    self :   List[Any]					):


       """simple docstring"""







       UpperCamelCase      							=    MaskaFormerModel.from_pretrained(self.model_checkpoints					).to(UpperCamelCase__					)
       UpperCamelCase      							=    self.default_image_processor
       UpperCamelCase      							=    prepare_img()
       UpperCamelCase      							=    image_processor(UpperCamelCase__    ,		return_tensors='pt'					).to(UpperCamelCase__					)
       UpperCamelCase      							=    inputs['pixel_values'].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0					)
       # check size
       self.assertEqual(UpperCamelCase__    ,		(1, 3, 3_8_4, 3_8_4)					)

       with torch.no_grad():
          UpperCamelCase      							=    model(**UpperCamelCase__					)

       UpperCamelCase      							=    torch.tensor(
           [[-0.2_7_9_0, -1.0_7_1_7, -1.1_6_6_8], [-0.5_1_2_8, -0.3_1_2_8, -0.4_9_8_7], [-0.5_8_3_2, 0.1_9_7_1, -0.0_1_9_7]]					).to(UpperCamelCase__					)
       self.assertTrue(
           torch.allclose(
               outputs.encoder_last_hidden_state[0, 0, :3, :3]    ,		UpperCamelCase__    ,		atol=UpperCamelCase__					)					)

       UpperCamelCase      							=    torch.tensor(
           [[0.8_9_7_3, 1.1_8_4_7, 1.1_7_7_6], [1.1_9_3_4, 1.5_0_4_0, 1.5_1_2_8], [1.1_1_5_3, 1.4_4_8_6, 1.4_9_5_1]]					).to(UpperCamelCase__					)
       self.assertTrue(
           torch.allclose(
               outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]    ,		UpperCamelCase__    ,		atol=UpperCamelCase__					)					)

       UpperCamelCase      							=    torch.tensor(
           [[2.1_1_5_2, 1.7_0_0_0, -0.8_6_0_3], [1.5_8_0_8, 1.8_0_0_4, -0.9_3_5_3], [1.6_0_4_3, 1.7_4_9_5, -0.5_9_9_9]]					).to(UpperCamelCase__					)
       self.assertTrue(
           torch.allclose(
               outputs.transformer_decoder_last_hidden_state[0, :3, :3]    ,		UpperCamelCase__    ,		atol=UpperCamelCase__					)					)






    def 					A			(    self :   Tuple					):


       """simple docstring"""







       UpperCamelCase      							=    MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints					).to(UpperCamelCase__					).eval()
       UpperCamelCase      							=    self.default_image_processor
       UpperCamelCase      							=    prepare_img()
       UpperCamelCase      							=    image_processor(UpperCamelCase__    ,		return_tensors='pt'					).to(UpperCamelCase__					)
       UpperCamelCase      							=    inputs['pixel_values'].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0					)
       # check size
       self.assertEqual(UpperCamelCase__    ,		(1, 3, 3_8_4, 3_8_4)					)

       with torch.no_grad():
          UpperCamelCase      							=    model(**UpperCamelCase__					)
       # masks_queries_logits
       UpperCamelCase      							=    outputs.masks_queries_logits
       self.assertEqual(
           masks_queries_logits.shape    ,		(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)					)
       UpperCamelCase      							=    [
           [-8.7_8_3_9, -9.0_0_5_6, -8.8_1_2_1],
           [-7.4_1_0_4, -7.0_3_1_3, -6.5_4_0_1],
           [-6.6_1_0_5, -6.3_4_2_7, -6.4_6_7_5],
       ]
       UpperCamelCase      							=    torch.tensor(UpperCamelCase__					).to(UpperCamelCase__					)
       self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]    ,		UpperCamelCase__    ,		atol=UpperCamelCase__					)					)
       # class_queries_logits
       UpperCamelCase      							=    outputs.class_queries_logits
       self.assertEqual(class_queries_logits.shape    ,		(1, model.config.num_queries, model.config.num_labels + 1)					)
       UpperCamelCase      							=    torch.tensor(
           [
               [1.8_3_2_4, -8.0_8_3_5, -4.1_9_2_2],
               [0.8_4_5_0, -9.0_0_5_0, -3.6_0_5_3],
               [0.3_0_4_5, -7.7_2_9_3, -3.0_2_7_5],
           ]					).to(UpperCamelCase__					)
       self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]    ,		UpperCamelCase__    ,		atol=UpperCamelCase__					)					)






    def 					A			(    self :   List[Any]					):


       """simple docstring"""







       UpperCamelCase      							=    MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints					).to(UpperCamelCase__					).eval()
       UpperCamelCase      							=    self.default_image_processor

       UpperCamelCase      							=    image_processor(
           [np.zeros((3, 8_0_0, 1_3_3_3)					), np.zeros((3, 8_0_0, 1_3_3_3)					)]    ,		segmentation_maps=[np.zeros((3_8_4, 3_8_4)					).astype(np.floataa					), np.zeros((3_8_4, 3_8_4)					).astype(np.floataa					)]    ,		return_tensors='pt'    ,		)

       UpperCamelCase      							=    inputs['pixel_values'].to(UpperCamelCase__					)
       UpperCamelCase      							=    [el.to(UpperCamelCase__					) for el in inputs['mask_labels']]
       UpperCamelCase      							=    [el.to(UpperCamelCase__					) for el in inputs['class_labels']]

       with torch.no_grad():
          UpperCamelCase      							=    model(**UpperCamelCase__					)

       self.assertTrue(outputs.loss is not None					)



from collections.abc import Sequence


def 				__A(lowerCAmelCase = None			)		->					int:

		"""simple docstring"""






		if nums is None or not nums:
				raise ValueError("""Input sequence should not be empty"""			)

		_UpperCamelCase         =						nums[0]
		for i in range(1    ,	len(lowerCAmelCase			)			):
				_UpperCamelCase         =						nums[i]
				_UpperCamelCase         =						max(lowerCAmelCase    ,	ans + num    ,	lowerCAmelCase			)

		return ans


if __name__ == "__main__":
		import doctest

		doctest.testmod()

		# Try on a sample input from the user
		lowerCamelCase__						=				int(input("Enter number of elements : ").strip())
		lowerCamelCase__						=				list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
		print(max_subsequence_sum(array))



