import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, 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 MaskFormerForInstanceSegmentation, MaskFormerModel

      if is_vision_available():
            from transformers import MaskFormerImageProcessor

if is_vision_available():
      from PIL import Image






class 		_lowerCamelCase		:
    def __init__(  self , lowerCAmelCase , lowerCAmelCase=2 , lowerCAmelCase=True , lowerCAmelCase=False , lowerCAmelCase=10 , lowerCAmelCase=3 , lowerCAmelCase=32 * 4 , lowerCAmelCase=32 * 6 , lowerCAmelCase=4 , lowerCAmelCase=32 , )       ->					Any:
     SCREAMING_SNAKE_CASE__:   List[str]=      parent
     SCREAMING_SNAKE_CASE__:   str=      batch_size
     SCREAMING_SNAKE_CASE__:   List[str]=      is_training
     SCREAMING_SNAKE_CASE__:   Tuple=      use_auxiliary_loss
     SCREAMING_SNAKE_CASE__:   Optional[Any]=      num_queries
     SCREAMING_SNAKE_CASE__:   Optional[int]=      num_channels
     SCREAMING_SNAKE_CASE__:   Union[str, Any]=      min_size
     SCREAMING_SNAKE_CASE__:   Any=      max_size
     SCREAMING_SNAKE_CASE__:   Any=      num_labels
     SCREAMING_SNAKE_CASE__:   Union[str, Any]=      mask_feature_size
    def 						UpperCamelCase_				(  self   )       ->					Dict:
     SCREAMING_SNAKE_CASE__:   Any=      floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]   ).to(
         lowerCAmelCase   )

     SCREAMING_SNAKE_CASE__:   Dict=      torch.ones([self.batch_size, self.min_size, self.max_size] , device=lowerCAmelCase   )

     SCREAMING_SNAKE_CASE__:   int=      (
         torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=lowerCAmelCase   ) > 0.5
     ).float()
     SCREAMING_SNAKE_CASE__:   List[Any]=      (torch.rand((self.batch_size, self.num_labels) , device=lowerCAmelCase   ) > 0.5).long()

     SCREAMING_SNAKE_CASE__:   Optional[int]=      self.get_config()
     return config, pixel_values, pixel_mask, mask_labels, class_labels
    def 						UpperCamelCase_				(  self   )       ->					Any:
     return MaskFormerConfig.from_backbone_and_decoder_configs(
         backbone_config=SwinConfig(
             depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
             decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
    def 						UpperCamelCase_				(  self   )       ->					List[Any]:
     SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__:   Union[str, Any]=      self.prepare_config_and_inputs()
     SCREAMING_SNAKE_CASE__:   str=      {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
     return config, inputs_dict
    def 						UpperCamelCase_				(  self , lowerCAmelCase , lowerCAmelCase   )       ->					List[str]:
     SCREAMING_SNAKE_CASE__:   Tuple=      output.encoder_hidden_states
     SCREAMING_SNAKE_CASE__:   str=      output.pixel_decoder_hidden_states
     SCREAMING_SNAKE_CASE__:   Tuple=      output.transformer_decoder_hidden_states

     self.parent.assertTrue(len(lowerCAmelCase   ) , len(config.backbone_config.depths   )   )
     self.parent.assertTrue(len(lowerCAmelCase   ) , len(config.backbone_config.depths   )   )
     self.parent.assertTrue(len(lowerCAmelCase   ) , config.decoder_config.decoder_layers   )
    def 						UpperCamelCase_				(  self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False   )       ->					Optional[Any]:
     with torch.no_grad():
      SCREAMING_SNAKE_CASE__:   str=      MaskFormerModel(config=lowerCAmelCase   )
      model.to(lowerCAmelCase   )
      model.eval()

      SCREAMING_SNAKE_CASE__:   Dict=      model(pixel_values=lowerCAmelCase , pixel_mask=lowerCAmelCase   )
      SCREAMING_SNAKE_CASE__:   int=      model(lowerCAmelCase , output_hidden_states=lowerCAmelCase   )
     # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
     # encoder and pixel decoder
     self.parent.assertEqual(
         output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
     # 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(lowerCAmelCase , lowerCAmelCase   )



    def 						UpperCamelCase_				(  self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase   )       ->					List[Any]:
     SCREAMING_SNAKE_CASE__:   List[Any]=      MaskFormerForInstanceSegmentation(config=lowerCAmelCase   )
     model.to(lowerCAmelCase   )
     model.eval()

     def comm_check_on_output(lowerCAmelCase   ):
      # 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():
      SCREAMING_SNAKE_CASE__:   str=      model(pixel_values=lowerCAmelCase , pixel_mask=lowerCAmelCase   )
      SCREAMING_SNAKE_CASE__:   Union[str, Any]=      model(lowerCAmelCase   )

      comm_check_on_output(lowerCAmelCase   )

      SCREAMING_SNAKE_CASE__:   List[str]=      model(
          pixel_values=lowerCAmelCase , pixel_mask=lowerCAmelCase , mask_labels=lowerCAmelCase , class_labels=lowerCAmelCase   )

     comm_check_on_output(lowerCAmelCase   )

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






@require_torch
class 		_lowerCamelCase		(   UpperCamelCase_    ,     UpperCamelCase_    ,     unittest.TestCase    ):
    __a  =      (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
    __a  =      (
        {"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
        if is_torch_available()
        else {}
    )

    __a  =      False
    __a  =      False
    __a  =      False
    __a  =      False
    def 						UpperCamelCase_				(  self   )       ->					List[str]:
     SCREAMING_SNAKE_CASE__:   Tuple=      MaskFormerModelTester(self   )
     SCREAMING_SNAKE_CASE__:   Dict=      ConfigTester(self , config_class=lowerCAmelCase , has_text_modality=lowerCAmelCase   )
    def 						UpperCamelCase_				(  self   )       ->					List[Any]:
     self.config_tester.run_common_tests()
    def 						UpperCamelCase_				(  self   )       ->					List[str]:
     SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__:   List[Any]=      self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.create_and_check_maskformer_model(lowerCAmelCase , **lowerCAmelCase , output_hidden_states=lowerCAmelCase   )
    def 						UpperCamelCase_				(  self   )       ->					List[Any]:
     SCREAMING_SNAKE_CASE__:   int=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*lowerCAmelCase   )
    @unittest.skip(reason='''MaskFormer does not use inputs_embeds'''   )
    def 						UpperCamelCase_				(  self   )       ->					Optional[int]:
     pass
    @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method'''   )
    def 						UpperCamelCase_				(  self   )       ->					Union[str, Any]:
     pass
    @unittest.skip(reason='''MaskFormer is not a generative model'''   )
    def 						UpperCamelCase_				(  self   )       ->					int:
     pass
    @unittest.skip(reason='''MaskFormer does not use token embeddings'''   )
    def 						UpperCamelCase_				(  self   )       ->					Optional[Any]:
     pass
    @require_torch_multi_gpu
    @unittest.skip(
        reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''   )
    def 						UpperCamelCase_				(  self   )       ->					Dict:
     pass
    @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
    def 						UpperCamelCase_				(  self   )       ->					Optional[int]:
     pass
    def 						UpperCamelCase_				(  self   )       ->					Optional[Any]:
     SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__:   Optional[int]=      self.model_tester.prepare_config_and_inputs_for_common()

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

      SCREAMING_SNAKE_CASE__:   int=      ['''pixel_values''']
      self.assertListEqual(arg_names[:1] , lowerCAmelCase   )
    @slow
    def 						UpperCamelCase_				(  self   )       ->					List[Any]:
     for model_name in ["facebook/maskformer-swin-small-coco"]:
      SCREAMING_SNAKE_CASE__:   Any=      MaskFormerModel.from_pretrained(lowerCAmelCase   )
      self.assertIsNotNone(lowerCAmelCase   )
    def 						UpperCamelCase_				(  self   )       ->					Optional[Any]:
     SCREAMING_SNAKE_CASE__:   Tuple=      (self.model_tester.min_size,) * 2
     SCREAMING_SNAKE_CASE__:   int=      {
         '''pixel_values''': torch.randn((2, 3, *size) , device=lowerCAmelCase   ),
         '''mask_labels''': torch.randn((2, 10, *size) , device=lowerCAmelCase   ),
         '''class_labels''': torch.zeros(2 , 10 , device=lowerCAmelCase   ).long(),
     }

     SCREAMING_SNAKE_CASE__:   Any=      MaskFormerForInstanceSegmentation(MaskFormerConfig()   ).to(lowerCAmelCase   )
     SCREAMING_SNAKE_CASE__:   str=      model(**lowerCAmelCase   )
     self.assertTrue(outputs.loss is not None   )
    def 						UpperCamelCase_				(  self   )       ->					Optional[int]:
     SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__:   int=      self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.create_and_check_maskformer_model(lowerCAmelCase , **lowerCAmelCase , output_hidden_states=lowerCAmelCase   )
    def 						UpperCamelCase_				(  self   )       ->					List[Any]:
     SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__:   Optional[int]=      self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
      SCREAMING_SNAKE_CASE__:   str=      model_class(lowerCAmelCase   ).to(lowerCAmelCase   )
      SCREAMING_SNAKE_CASE__:   Dict=      model(**lowerCAmelCase , output_attentions=lowerCAmelCase   )
      self.assertTrue(outputs.attentions is not None   )
    def 						UpperCamelCase_				(  self   )       ->					List[str]:
     if not self.model_tester.is_training:
      return
     # only MaskFormerForInstanceSegmentation has the loss
     SCREAMING_SNAKE_CASE__:   Union[str, Any]=      self.all_model_classes[1]
     SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__:   Dict=      self.model_tester.prepare_config_and_inputs()

     SCREAMING_SNAKE_CASE__:   List[Any]=      model_class(lowerCAmelCase   )
     model.to(lowerCAmelCase   )
     model.train()

     SCREAMING_SNAKE_CASE__:   Union[str, Any]=      model(lowerCAmelCase , mask_labels=lowerCAmelCase , class_labels=lowerCAmelCase   ).loss
     loss.backward()



    def 						UpperCamelCase_				(  self   )       ->					Optional[int]:
     # only MaskFormerForInstanceSegmentation has the loss
     SCREAMING_SNAKE_CASE__:   Optional[int]=      self.all_model_classes[1]
     SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__:   Dict=      self.model_tester.prepare_config_and_inputs()
     SCREAMING_SNAKE_CASE__:   Dict=      True
     SCREAMING_SNAKE_CASE__:   Optional[int]=      True

     SCREAMING_SNAKE_CASE__:   Union[str, Any]=      model_class(lowerCAmelCase   )
     model.to(lowerCAmelCase   )
     model.train()

     SCREAMING_SNAKE_CASE__:   int=      model(lowerCAmelCase , mask_labels=lowerCAmelCase , class_labels=lowerCAmelCase   )

     SCREAMING_SNAKE_CASE__:   Optional[int]=      outputs.encoder_hidden_states[0]
     encoder_hidden_states.retain_grad()

     SCREAMING_SNAKE_CASE__:   List[str]=      outputs.pixel_decoder_hidden_states[0]
     pixel_decoder_hidden_states.retain_grad()
     # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
     SCREAMING_SNAKE_CASE__:   List[str]=      outputs.transformer_decoder_hidden_states[0]
     transformer_decoder_hidden_states.retain_grad()

     SCREAMING_SNAKE_CASE__:   Any=      outputs.attentions[0]
     attentions.retain_grad()

     outputs.loss.backward(retain_graph=lowerCAmelCase   )

     self.assertIsNotNone(encoder_hidden_states.grad   )
     self.assertIsNotNone(pixel_decoder_hidden_states.grad   )
     self.assertIsNotNone(transformer_decoder_hidden_states.grad   )
     self.assertIsNotNone(attentions.grad   )
lowercase_     :   int 				=				1E-4







def 			A__      (	):
 SCREAMING_SNAKE_CASE__:   Tuple=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
 return image






@require_vision
@slow
class 		_lowerCamelCase		(   unittest.TestCase    ):
    @cached_property
    def 						UpperCamelCase_				(  self   )       ->					List[Any]:
     return (
         MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco'''   )
         if is_vision_available()
         else None
     )
    def 						UpperCamelCase_				(  self   )       ->					Tuple:
     SCREAMING_SNAKE_CASE__:   str=      MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco'''   ).to(lowerCAmelCase   )
     SCREAMING_SNAKE_CASE__:   Any=      self.default_image_processor
     SCREAMING_SNAKE_CASE__:   Optional[Any]=      prepare_img()
     SCREAMING_SNAKE_CASE__:   Dict=      image_processor(lowerCAmelCase , return_tensors='''pt'''   ).to(lowerCAmelCase   )
     SCREAMING_SNAKE_CASE__:   str=      inputs['''pixel_values'''].shape
     # check size is divisible by 32
     self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0   )
     # check size
     self.assertEqual(lowerCAmelCase , (1, 3, 800, 1088)   )

     with torch.no_grad():
      SCREAMING_SNAKE_CASE__:   List[Any]=      model(**lowerCAmelCase   )

     SCREAMING_SNAKE_CASE__:   List[Any]=      torch.tensor(
         [[-0.0482, 0.9228, 0.4951], [-0.2547, 0.8017, 0.8527], [-0.0069, 0.3385, -0.0089]]   ).to(lowerCAmelCase   )
     self.assertTrue(
         torch.allclose(
             outputs.encoder_last_hidden_state[0, 0, :3, :3] , lowerCAmelCase , atol=lowerCAmelCase   )   )

     SCREAMING_SNAKE_CASE__:   Any=      torch.tensor(
         [[-0.8422, -0.8434, -0.9718], [-1.0144, -0.5565, -0.4195], [-1.0038, -0.4484, -0.1961]]   ).to(lowerCAmelCase   )
     self.assertTrue(
         torch.allclose(
             outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , lowerCAmelCase , atol=lowerCAmelCase   )   )

     SCREAMING_SNAKE_CASE__:   Optional[Any]=      torch.tensor(
         [[0.2852, -0.0159, 0.9735], [0.6254, 0.1858, 0.8529], [-0.0680, -0.4116, 1.8413]]   ).to(lowerCAmelCase   )
     self.assertTrue(
         torch.allclose(
             outputs.transformer_decoder_last_hidden_state[0, :3, :3] , lowerCAmelCase , atol=lowerCAmelCase   )   )
    def 						UpperCamelCase_				(  self   )       ->					List[Any]:
     SCREAMING_SNAKE_CASE__:   List[Any]=      (
         MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco'''   )
         .to(lowerCAmelCase   )
         .eval()
     )
     SCREAMING_SNAKE_CASE__:   List[str]=      self.default_image_processor
     SCREAMING_SNAKE_CASE__:   str=      prepare_img()
     SCREAMING_SNAKE_CASE__:   Any=      image_processor(lowerCAmelCase , return_tensors='''pt'''   ).to(lowerCAmelCase   )
     SCREAMING_SNAKE_CASE__:   List[str]=      inputs['''pixel_values'''].shape
     # check size is divisible by 32
     self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0   )
     # check size
     self.assertEqual(lowerCAmelCase , (1, 3, 800, 1088)   )

     with torch.no_grad():
      SCREAMING_SNAKE_CASE__:   Tuple=      model(**lowerCAmelCase   )
     # masks_queries_logits
     SCREAMING_SNAKE_CASE__:   Tuple=      outputs.masks_queries_logits
     self.assertEqual(
         masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
     SCREAMING_SNAKE_CASE__:   Any=      [
         [-1.3737124, -1.7724937, -1.9364233],
         [-1.5977281, -1.9867939, -2.1523695],
         [-1.5795398, -1.9269832, -2.093942],
     ]
     SCREAMING_SNAKE_CASE__:   Any=      torch.tensor(lowerCAmelCase   ).to(lowerCAmelCase   )
     self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , lowerCAmelCase , atol=lowerCAmelCase   )   )
     # class_queries_logits
     SCREAMING_SNAKE_CASE__:   str=      outputs.class_queries_logits
     self.assertEqual(
         class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)   )
     SCREAMING_SNAKE_CASE__:   List[str]=      torch.tensor(
         [
             [1.6512e00, -5.2572e00, -3.3519e00],
             [3.6169e-02, -5.9025e00, -2.9313e00],
             [1.0766e-04, -7.7630e00, -5.1263e00],
         ]   ).to(lowerCAmelCase   )
     self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , lowerCAmelCase , atol=lowerCAmelCase   )   )
    def 						UpperCamelCase_				(  self   )       ->					Optional[Any]:
     SCREAMING_SNAKE_CASE__:   Dict=      (
         MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff'''   )
         .to(lowerCAmelCase   )
         .eval()
     )
     SCREAMING_SNAKE_CASE__:   int=      self.default_image_processor
     SCREAMING_SNAKE_CASE__:   Optional[int]=      prepare_img()
     SCREAMING_SNAKE_CASE__:   str=      image_processor(lowerCAmelCase , return_tensors='''pt'''   ).to(lowerCAmelCase   )
     SCREAMING_SNAKE_CASE__:   List[Any]=      inputs['''pixel_values'''].shape
     # check size is divisible by 32
     self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0   )
     # check size
     self.assertEqual(lowerCAmelCase , (1, 3, 800, 1088)   )

     with torch.no_grad():
      SCREAMING_SNAKE_CASE__:   int=      model(**lowerCAmelCase   )
     # masks_queries_logits
     SCREAMING_SNAKE_CASE__:   int=      outputs.masks_queries_logits
     self.assertEqual(
         masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
     SCREAMING_SNAKE_CASE__:   str=      [[-0.9046, -2.6366, -4.6062], [-3.4179, -5.7890, -8.8057], [-4.9179, -7.6560, -10.7711]]
     SCREAMING_SNAKE_CASE__:   Optional[int]=      torch.tensor(lowerCAmelCase   ).to(lowerCAmelCase   )
     self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , lowerCAmelCase , atol=lowerCAmelCase   )   )
     # class_queries_logits
     SCREAMING_SNAKE_CASE__:   Union[str, Any]=      outputs.class_queries_logits
     self.assertEqual(
         class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)   )
     SCREAMING_SNAKE_CASE__:   List[str]=      torch.tensor(
         [[4.7188, -3.2585, -2.8857], [6.6871, -2.9181, -1.2487], [7.2449, -2.2764, -2.1874]]   ).to(lowerCAmelCase   )
     self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , lowerCAmelCase , atol=lowerCAmelCase   )   )



    def 						UpperCamelCase_				(  self   )       ->					str:
     SCREAMING_SNAKE_CASE__:   List[str]=      (
         MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco'''   )
         .to(lowerCAmelCase   )
         .eval()
     )
     SCREAMING_SNAKE_CASE__:   Any=      self.default_image_processor

     SCREAMING_SNAKE_CASE__:   List[Any]=      image_processor(
         [np.zeros((3, 800, 1333)   ), np.zeros((3, 800, 1333)   )] , segmentation_maps=[np.zeros((384, 384)   ).astype(np.floataa   ), np.zeros((384, 384)   ).astype(np.floataa   )] , return_tensors='''pt''' , )

     SCREAMING_SNAKE_CASE__:   Dict=      inputs['''pixel_values'''].to(lowerCAmelCase   )
     SCREAMING_SNAKE_CASE__:   int=      [el.to(lowerCAmelCase   ) for el in inputs['''mask_labels''']]
     SCREAMING_SNAKE_CASE__:   int=      [el.to(lowerCAmelCase   ) for el in inputs['''class_labels''']]

     with torch.no_grad():
      SCREAMING_SNAKE_CASE__:   List[str]=      model(**lowerCAmelCase   )

     self.assertTrue(outputs.loss is not None   )


def 			A__      (	snake_case_ :		str      ):
 if not head:
  return True
 # split the list to two parts
 SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__:   Optional[int]=      head.next, head
 while fast and fast.next:
  SCREAMING_SNAKE_CASE__:   Dict=      fast.next.next
  SCREAMING_SNAKE_CASE__:   Union[str, Any]=      slow.next
 SCREAMING_SNAKE_CASE__:   Union[str, Any]=      slow.next
 SCREAMING_SNAKE_CASE__:   Union[str, Any]=      None  # Don't forget here! But forget still works!
 # reverse the second part
 SCREAMING_SNAKE_CASE__:   Optional[int]=      None
 while second:
  SCREAMING_SNAKE_CASE__:   Any=      second.next
  SCREAMING_SNAKE_CASE__:   int=      node
  SCREAMING_SNAKE_CASE__:   Optional[Any]=      second
  SCREAMING_SNAKE_CASE__:   Any=      nxt
 # compare two parts
 # second part has the same or one less node
 while node:
  if node.val != head.val:
   return False
  SCREAMING_SNAKE_CASE__:   Tuple=      node.next
  SCREAMING_SNAKE_CASE__:   Optional[int]=      head.next
 return True







def 			A__      (	snake_case_ :		Optional[Any]      ):
 if not head or not head.next:
  return True

 # 1. Get the midpoint (slow)
 SCREAMING_SNAKE_CASE__:   List[Any]=      head
 while fast and fast.next:
  SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__:   Any=      fast.next.next, slow.next

 # 2. Push the second half into the stack
 SCREAMING_SNAKE_CASE__:   Optional[Any]=      [slow.val]
 while slow.next:
  SCREAMING_SNAKE_CASE__:   Optional[int]=      slow.next
  stack.append(slow.val      )

 # 3. Comparison
 while stack:
  if stack.pop() != cur.val:
   return False
  SCREAMING_SNAKE_CASE__:   Tuple=      cur.next

 return True







def 			A__      (	snake_case_ :		Any      ):
 if not head or not head.next:
  return True
 SCREAMING_SNAKE_CASE__:   Optional[int]=      {}
 SCREAMING_SNAKE_CASE__:   Union[str, Any]=      0
 while head:
  if head.val in d:
   d[head.val].append(snake_case_      )
  else:
   SCREAMING_SNAKE_CASE__:   Optional[int]=      [pos]
  SCREAMING_SNAKE_CASE__:   Dict=      head.next
  pos += 1
 SCREAMING_SNAKE_CASE__:   Dict=      pos - 1
 SCREAMING_SNAKE_CASE__:   str=      0
 for v in d.values():
  if len(snake_case_      ) % 2 != 0:
   middle += 1
  else:
   SCREAMING_SNAKE_CASE__:   List[Any]=      0
   for i in range(0       ,				len(snake_case_      )      ):
    if v[i] + v[len(snake_case_      ) - 1 - step] != checksum:
     return False
    step += 1
  if middle > 1:
   return False
 return True

