




'''simple docstring'''



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     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE=2     ,	__SCREAMING_SNAKE_CASE=True     ,	__SCREAMING_SNAKE_CASE=False     ,	__SCREAMING_SNAKE_CASE=10     ,	__SCREAMING_SNAKE_CASE=3     ,	__SCREAMING_SNAKE_CASE=32 * 4     ,	__SCREAMING_SNAKE_CASE=32 * 6     ,	__SCREAMING_SNAKE_CASE=4     ,	__SCREAMING_SNAKE_CASE=32     ,	)   ->	Any:



            '''simple docstring'''




            __snake_case            =	parent
            __snake_case            =	batch_size
            __snake_case            =	is_training
            __snake_case            =	use_auxiliary_loss
            __snake_case            =	num_queries
            __snake_case            =	num_channels
            __snake_case            =	min_size
            __snake_case            =	max_size
            __snake_case            =	num_labels
            __snake_case            =	mask_feature_size


       def    lowerCAmelCase   ( self	)   ->	Tuple:



            '''simple docstring'''




            __snake_case            =	floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]	).to(
                __SCREAMING_SNAKE_CASE	)

            __snake_case            =	torch.ones([self.batch_size, self.min_size, self.max_size]     ,	device=__SCREAMING_SNAKE_CASE	)

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

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


       def    lowerCAmelCase   ( self	)   ->	Tuple:



            '''simple docstring'''




            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    lowerCAmelCase   ( self	)   ->	Any:



            '''simple docstring'''




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


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	)   ->	Tuple:



            '''simple docstring'''




            __snake_case            =	output.encoder_hidden_states
            __snake_case            =	output.pixel_decoder_hidden_states
            __snake_case            =	output.transformer_decoder_hidden_states

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


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE=False	)   ->	Any:



            '''simple docstring'''




            with torch.no_grad():
                 __snake_case            =	MaskFormerModel(config=__SCREAMING_SNAKE_CASE	)
                 model.to(__SCREAMING_SNAKE_CASE	)
                 model.eval()

                 __snake_case            =	model(pixel_values=__SCREAMING_SNAKE_CASE     ,	pixel_mask=__SCREAMING_SNAKE_CASE	)
                 __snake_case            =	model(__SCREAMING_SNAKE_CASE     ,	output_hidden_states=__SCREAMING_SNAKE_CASE	)
            # 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(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	)




       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	)   ->	Optional[Any]:



            '''simple docstring'''




            __snake_case            =	MaskFormerForInstanceSegmentation(config=__SCREAMING_SNAKE_CASE	)
            model.to(__SCREAMING_SNAKE_CASE	)
            model.eval()

            def comm_check_on_output(__SCREAMING_SNAKE_CASE	):
                 # 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():
                 __snake_case            =	model(pixel_values=__SCREAMING_SNAKE_CASE     ,	pixel_mask=__SCREAMING_SNAKE_CASE	)
                 __snake_case            =	model(__SCREAMING_SNAKE_CASE	)

                 comm_check_on_output(__SCREAMING_SNAKE_CASE	)

                 __snake_case            =	model(
                     pixel_values=__SCREAMING_SNAKE_CASE     ,	pixel_mask=__SCREAMING_SNAKE_CASE     ,	mask_labels=__SCREAMING_SNAKE_CASE     ,	class_labels=__SCREAMING_SNAKE_CASE	)

            comm_check_on_output(__SCREAMING_SNAKE_CASE	)

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





@require_torch
class      lowerCAmelCase (			__lowerCAmelCase					, __lowerCAmelCase					, unittest.TestCase):
       __lowercase	:   Union[str, Any]										=      (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
       __lowercase	:   Union[str, Any]										=      (
           {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
           if is_torch_available()
           else {}
       )

       __lowercase	:   Any										=      False
       __lowercase	:   Any										=      False
       __lowercase	:   Optional[Any]										=      False
       __lowercase	:   Optional[Any]										=      False


       def    lowerCAmelCase   ( self	)   ->	Any:



            '''simple docstring'''




            __snake_case            =	MaskFormerModelTester(self	)
            __snake_case            =	ConfigTester(self     ,	config_class=__SCREAMING_SNAKE_CASE     ,	has_text_modality=__SCREAMING_SNAKE_CASE	)


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



            '''simple docstring'''




            self.config_tester.run_common_tests()


       def    lowerCAmelCase   ( self	)   ->	str:



            '''simple docstring'''




            __snake_case       ,     __snake_case            =	self.model_tester.prepare_config_and_inputs_for_common()
            self.model_tester.create_and_check_maskformer_model(__SCREAMING_SNAKE_CASE     ,	**__SCREAMING_SNAKE_CASE     ,	output_hidden_states=__SCREAMING_SNAKE_CASE	)


       def    lowerCAmelCase   ( self	)   ->	Optional[Any]:



            '''simple docstring'''




            __snake_case            =	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__SCREAMING_SNAKE_CASE	)


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



            '''simple docstring'''




            pass


       @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method'''	)
       def    lowerCAmelCase   ( self	)   ->	List[Any]:



            '''simple docstring'''




            pass


       @unittest.skip(reason='''MaskFormer is not a generative model'''	)
       def    lowerCAmelCase   ( self	)   ->	Any:



            '''simple docstring'''




            pass


       @unittest.skip(reason='''MaskFormer does not use token embeddings'''	)
       def    lowerCAmelCase   ( self	)   ->	Union[str, Any]:



            '''simple docstring'''




            pass


       @require_torch_multi_gpu
       @unittest.skip(
           reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''	)
       def    lowerCAmelCase   ( self	)   ->	Tuple:



            '''simple docstring'''




            pass


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



            '''simple docstring'''




            pass


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



            '''simple docstring'''




            __snake_case       ,     __snake_case            =	self.model_tester.prepare_config_and_inputs_for_common()

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

                 __snake_case            =	['''pixel_values''']
                 self.assertListEqual(arg_names[:1]     ,	__SCREAMING_SNAKE_CASE	)


       @slow
       def    lowerCAmelCase   ( self	)   ->	Dict:



            '''simple docstring'''




            for model_name in ["facebook/maskformer-swin-small-coco"]:
                 __snake_case            =	MaskFormerModel.from_pretrained(__SCREAMING_SNAKE_CASE	)
                 self.assertIsNotNone(__SCREAMING_SNAKE_CASE	)


       def    lowerCAmelCase   ( self	)   ->	Any:



            '''simple docstring'''




            __snake_case            =	(self.model_tester.min_size,) * 2
            __snake_case            =	{
                '''pixel_values''': torch.randn((2, 3, *size)     ,	device=__SCREAMING_SNAKE_CASE	),
                '''mask_labels''': torch.randn((2, 10, *size)     ,	device=__SCREAMING_SNAKE_CASE	),
                '''class_labels''': torch.zeros(2     ,	10     ,	device=__SCREAMING_SNAKE_CASE	).long(),
            }

            __snake_case            =	MaskFormerForInstanceSegmentation(MaskFormerConfig()	).to(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	model(**__SCREAMING_SNAKE_CASE	)
            self.assertTrue(outputs.loss is not None	)


       def    lowerCAmelCase   ( self	)   ->	Union[str, Any]:



            '''simple docstring'''




            __snake_case       ,     __snake_case            =	self.model_tester.prepare_config_and_inputs_for_common()
            self.model_tester.create_and_check_maskformer_model(__SCREAMING_SNAKE_CASE     ,	**__SCREAMING_SNAKE_CASE     ,	output_hidden_states=__SCREAMING_SNAKE_CASE	)


       def    lowerCAmelCase   ( self	)   ->	Union[str, Any]:



            '''simple docstring'''




            __snake_case       ,     __snake_case            =	self.model_tester.prepare_config_and_inputs_for_common()

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


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



            '''simple docstring'''




            if not self.model_tester.is_training:
                 return
            # only MaskFormerForInstanceSegmentation has the loss
            __snake_case            =	self.all_model_classes[1]
            __snake_case       ,     __snake_case       ,     __snake_case       ,     __snake_case       ,     __snake_case            =	self.model_tester.prepare_config_and_inputs()

            __snake_case            =	model_class(__SCREAMING_SNAKE_CASE	)
            model.to(__SCREAMING_SNAKE_CASE	)
            model.train()

            __snake_case            =	model(__SCREAMING_SNAKE_CASE     ,	mask_labels=__SCREAMING_SNAKE_CASE     ,	class_labels=__SCREAMING_SNAKE_CASE	).loss
            loss.backward()




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



            '''simple docstring'''




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

            __snake_case            =	model_class(__SCREAMING_SNAKE_CASE	)
            model.to(__SCREAMING_SNAKE_CASE	)
            model.train()

            __snake_case            =	model(__SCREAMING_SNAKE_CASE     ,	mask_labels=__SCREAMING_SNAKE_CASE     ,	class_labels=__SCREAMING_SNAKE_CASE	)

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

            __snake_case            =	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
            __snake_case            =	outputs.transformer_decoder_hidden_states[0]
            transformer_decoder_hidden_states.retain_grad()

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

            outputs.loss.backward(retain_graph=__SCREAMING_SNAKE_CASE	)

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





UpperCAmelCase_							:	List[str]	     =		1E-4







def       _UpperCamelCase			()-> str:




     '''simple docstring'''





     __snake_case            =	Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
     return image







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


       @cached_property
       def    lowerCAmelCase   ( self	)   ->	Dict:



            '''simple docstring'''




            return (
                MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco'''	)
                if is_vision_available()
                else None
            )


       def    lowerCAmelCase   ( self	)   ->	Dict:



            '''simple docstring'''




            __snake_case            =	MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco'''	).to(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	self.default_image_processor
            __snake_case            =	prepare_img()
            __snake_case            =	image_processor(__SCREAMING_SNAKE_CASE     ,	return_tensors='''pt'''	).to(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	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(__SCREAMING_SNAKE_CASE     ,	(1, 3, 800, 1088)	)

            with torch.no_grad():
                 __snake_case            =	model(**__SCREAMING_SNAKE_CASE	)

            __snake_case            =	torch.tensor(
                [[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]]	).to(__SCREAMING_SNAKE_CASE	)
            self.assertTrue(
                torch.allclose(
                    outputs.encoder_last_hidden_state[0, 0, :3, :3]     ,	__SCREAMING_SNAKE_CASE     ,	atol=__SCREAMING_SNAKE_CASE	)	)

            __snake_case            =	torch.tensor(
                [[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]]	).to(__SCREAMING_SNAKE_CASE	)
            self.assertTrue(
                torch.allclose(
                    outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]     ,	__SCREAMING_SNAKE_CASE     ,	atol=__SCREAMING_SNAKE_CASE	)	)

            __snake_case            =	torch.tensor(
                [[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]]	).to(__SCREAMING_SNAKE_CASE	)
            self.assertTrue(
                torch.allclose(
                    outputs.transformer_decoder_last_hidden_state[0, :3, :3]     ,	__SCREAMING_SNAKE_CASE     ,	atol=__SCREAMING_SNAKE_CASE	)	)


       def    lowerCAmelCase   ( self	)   ->	int:



            '''simple docstring'''




            __snake_case            =	(
                MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco'''	)
                .to(__SCREAMING_SNAKE_CASE	)
                .eval()
            )
            __snake_case            =	self.default_image_processor
            __snake_case            =	prepare_img()
            __snake_case            =	image_processor(__SCREAMING_SNAKE_CASE     ,	return_tensors='''pt'''	).to(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	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(__SCREAMING_SNAKE_CASE     ,	(1, 3, 800, 1088)	)

            with torch.no_grad():
                 __snake_case            =	model(**__SCREAMING_SNAKE_CASE	)
            # masks_queries_logits
            __snake_case            =	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)     ,	)
            __snake_case            =	[
                [-1.3_737_124, -1.7_724_937, -1.9_364_233],
                [-1.5_977_281, -1.9_867_939, -2.1_523_695],
                [-1.5_795_398, -1.9_269_832, -2.093_942],
            ]
            __snake_case            =	torch.tensor(__SCREAMING_SNAKE_CASE	).to(__SCREAMING_SNAKE_CASE	)
            self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]     ,	__SCREAMING_SNAKE_CASE     ,	atol=__SCREAMING_SNAKE_CASE	)	)
            # class_queries_logits
            __snake_case            =	outputs.class_queries_logits
            self.assertEqual(
                class_queries_logits.shape     ,	(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)	)
            __snake_case            =	torch.tensor(
                [
                    [1.65_12E00, -5.25_72E00, -3.35_19E00],
                    [3.61_69E-02, -5.90_25E00, -2.93_13E00],
                    [1.07_66E-04, -7.76_30E00, -5.12_63E00],
                ]	).to(__SCREAMING_SNAKE_CASE	)
            self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]     ,	__SCREAMING_SNAKE_CASE     ,	atol=__SCREAMING_SNAKE_CASE	)	)


       def    lowerCAmelCase   ( self	)   ->	str:



            '''simple docstring'''




            __snake_case            =	(
                MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff'''	)
                .to(__SCREAMING_SNAKE_CASE	)
                .eval()
            )
            __snake_case            =	self.default_image_processor
            __snake_case            =	prepare_img()
            __snake_case            =	image_processor(__SCREAMING_SNAKE_CASE     ,	return_tensors='''pt'''	).to(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	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(__SCREAMING_SNAKE_CASE     ,	(1, 3, 800, 1088)	)

            with torch.no_grad():
                 __snake_case            =	model(**__SCREAMING_SNAKE_CASE	)
            # masks_queries_logits
            __snake_case            =	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)     ,	)
            __snake_case            =	[[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
            __snake_case            =	torch.tensor(__SCREAMING_SNAKE_CASE	).to(__SCREAMING_SNAKE_CASE	)
            self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]     ,	__SCREAMING_SNAKE_CASE     ,	atol=__SCREAMING_SNAKE_CASE	)	)
            # class_queries_logits
            __snake_case            =	outputs.class_queries_logits
            self.assertEqual(
                class_queries_logits.shape     ,	(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)	)
            __snake_case            =	torch.tensor(
                [[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]]	).to(__SCREAMING_SNAKE_CASE	)
            self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]     ,	__SCREAMING_SNAKE_CASE     ,	atol=__SCREAMING_SNAKE_CASE	)	)




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



            '''simple docstring'''




            __snake_case            =	(
                MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco'''	)
                .to(__SCREAMING_SNAKE_CASE	)
                .eval()
            )
            __snake_case            =	self.default_image_processor

            __snake_case            =	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'''     ,	)

            __snake_case            =	inputs['''pixel_values'''].to(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	[el.to(__SCREAMING_SNAKE_CASE	) for el in inputs['''mask_labels''']]
            __snake_case            =	[el.to(__SCREAMING_SNAKE_CASE	) for el in inputs['''class_labels''']]

            with torch.no_grad():
                 __snake_case            =	model(**__SCREAMING_SNAKE_CASE	)

            self.assertTrue(outputs.loss is not None	)












'''simple docstring'''



import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('''3.8'''):
     import importlib_metadata
else:
     import importlib.metadata as importlib_metadata







def       _UpperCamelCase			(_lowerCamelCase				:  List[Any] ,						_lowerCamelCase				:  Tuple=False						)-> Union[str, Any]:




     '''simple docstring'''





     try:
          __snake_case            =	os.environ[key]
     except KeyError:
          # KEY isn't set, default to `default`.
          __snake_case            =	default
     else:
          # KEY is set, convert it to True or False.
          try:
               __snake_case            =	strtobool(_lowerCamelCase						)
          except ValueError:
               # More values are supported, but let's keep the message simple.
               raise ValueError(f'''If set, {key} must be yes or no.'''						)
     return _value


UpperCAmelCase_							:	Optional[Any]	     =		parse_flag_from_env('''RUN_SLOW''', default=False)
UpperCAmelCase_							:	Union[str, Any]	     =		parse_flag_from_env('''RUN_REMOTE''', default=False)
UpperCAmelCase_							:	Optional[Any]	     =		parse_flag_from_env('''RUN_LOCAL''', default=True)
UpperCAmelCase_							:	Union[str, Any]	     =		parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
UpperCAmelCase_							:	Dict	     =		pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
UpperCAmelCase_							:	int	     =		pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
UpperCAmelCase_							:	Tuple	     =		pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
UpperCAmelCase_							:	str	     =		pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''),
    reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''',
)

# Beam
UpperCAmelCase_							:	Tuple	     =		pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''),
    reason='''test requires apache-beam and a compatible dill version''',
)

# Dill-cloudpickle compatibility
UpperCAmelCase_							:	Union[str, Any]	     =		pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

# Windows
UpperCAmelCase_							:	int	     =		pytest.mark.skipif(
    sys.platform == '''win32''',
    reason='''test should not be run on Windows''',
)







def       _UpperCamelCase			(_lowerCamelCase				:  List[str]						)-> List[Any]:




     '''simple docstring'''





     try:
          import faiss  # noqa
     except ImportError:
          __snake_case            =	unittest.skip('''test requires faiss'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Union[str, Any]						)-> List[str]:




     '''simple docstring'''





     try:
          import regex  # noqa
     except ImportError:
          __snake_case            =	unittest.skip('''test requires regex'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Union[str, Any]						)-> Union[str, Any]:




     '''simple docstring'''





     try:
          import elasticsearch  # noqa
     except ImportError:
          __snake_case            =	unittest.skip('''test requires elasticsearch'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Dict						)-> List[Any]:




     '''simple docstring'''





     try:
          import sqlalchemy  # noqa
     except ImportError:
          __snake_case            =	unittest.skip('''test requires sqlalchemy'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  List[str]						)-> List[str]:




     '''simple docstring'''





     if not config.TORCH_AVAILABLE:
          __snake_case            =	unittest.skip('''test requires PyTorch'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Optional[Any]						)-> Dict:




     '''simple docstring'''





     if not config.TF_AVAILABLE:
          __snake_case            =	unittest.skip('''test requires TensorFlow'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> Any:




     '''simple docstring'''





     if not config.JAX_AVAILABLE:
          __snake_case            =	unittest.skip('''test requires JAX'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Tuple						)-> str:




     '''simple docstring'''





     if not config.PIL_AVAILABLE:
          __snake_case            =	unittest.skip('''test requires Pillow'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Dict						)-> Any:




     '''simple docstring'''





     try:
          import transformers  # noqa F401
     except ImportError:
          return unittest.skip('''test requires transformers'''						)(_lowerCamelCase						)
     else:
          return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> Tuple:




     '''simple docstring'''





     try:
          import tiktoken  # noqa F401
     except ImportError:
          return unittest.skip('''test requires tiktoken'''						)(_lowerCamelCase						)
     else:
          return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Dict						)-> str:




     '''simple docstring'''





     try:
          import spacy  # noqa F401
     except ImportError:
          return unittest.skip('''test requires spacy'''						)(_lowerCamelCase						)
     else:
          return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> Dict:




     '''simple docstring'''





     def _require_spacy_model(_lowerCamelCase				:  int						):
          try:
               import spacy  # noqa F401

               spacy.load(_lowerCamelCase						)
          except ImportError:
               return unittest.skip('''test requires spacy'''						)(_lowerCamelCase						)
          except OSError:
               return unittest.skip('''test requires spacy model \'{}\''''.format(_lowerCamelCase						)						)(_lowerCamelCase						)
          else:
               return test_case

     return _require_spacy_model







def       _UpperCamelCase			(_lowerCamelCase				:  str						)-> Dict:




     '''simple docstring'''





     try:
          import pyspark  # noqa F401
     except ImportError:
          return unittest.skip('''test requires pyspark'''						)(_lowerCamelCase						)
     else:
          return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Tuple						)-> str:




     '''simple docstring'''





     try:
          import joblibspark  # noqa F401
     except ImportError:
          return unittest.skip('''test requires joblibspark'''						)(_lowerCamelCase						)
     else:
          return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Any						)-> int:




     '''simple docstring'''





     if not _run_slow_tests or _run_slow_tests == 0:
          __snake_case            =	unittest.skip('''test is slow'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Any						)-> Optional[Any]:




     '''simple docstring'''





     if not _run_local_tests or _run_local_tests == 0:
          __snake_case            =	unittest.skip('''test is local'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  str						)-> int:




     '''simple docstring'''





     if not _run_packaged_tests or _run_packaged_tests == 0:
          __snake_case            =	unittest.skip('''test is packaged'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Optional[int]						)-> str:




     '''simple docstring'''





     if not _run_remote_tests or _run_remote_tests == 0:
          __snake_case            =	unittest.skip('''test requires remote'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(*_lowerCamelCase				:  str						)-> Optional[int]:




     '''simple docstring'''





     def decorate(cls				:  Optional[Any]						):
          for name, fn in cls.__dict__.items():
               if callable(_lowerCamelCase						) and name.startswith('''test'''						):
                    for decorator in decorators:
                         __snake_case            =	decorator(_lowerCamelCase						)
                    setattr(cls ,						_lowerCamelCase ,						_lowerCamelCase						)
          return cls

     return decorate





class      lowerCAmelCase (			__lowerCAmelCase):
       pass





class      lowerCAmelCase (			__lowerCAmelCase):
       __lowercase	:   List[str]										=      0
       __lowercase	:   Dict										=      1
       __lowercase	:   List[Any]										=      2







@contextmanager
def       _UpperCamelCase			(_lowerCamelCase				:  Dict=OfflineSimulationMode.CONNECTION_FAILS ,						_lowerCamelCase				:  Optional[int]=1E-16						)-> Tuple:




     '''simple docstring'''





     __snake_case            =	requests.Session().request

     def timeout_request(_lowerCamelCase				:  Any ,						_lowerCamelCase				:  str ,						_lowerCamelCase				:  str ,						**_lowerCamelCase				:  Any						):
          # Change the url to an invalid url so that the connection hangs
          __snake_case            =	'''https://10.255.255.1'''
          if kwargs.get('''timeout'''						) is None:
               raise RequestWouldHangIndefinitelyError(
                   f'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'''						)
          __snake_case            =	timeout
          try:
               return online_request(_lowerCamelCase ,						_lowerCamelCase ,						**_lowerCamelCase						)
          except Exception as e:
               # The following changes in the error are just here to make the offline timeout error prettier
               __snake_case            =	url
               __snake_case            =	e.args[0]
               __snake_case            =	(max_retry_error.args[0].replace('''10.255.255.1''' ,						f'''OfflineMock[{url}]'''						),)
               __snake_case            =	(max_retry_error,)
               raise

     def raise_connection_error(_lowerCamelCase				:  Union[str, Any] ,						_lowerCamelCase				:  Optional[int] ,						**_lowerCamelCase				:  Dict						):
          raise requests.ConnectionError('''Offline mode is enabled.''' ,						request=_lowerCamelCase						)

     if mode is OfflineSimulationMode.CONNECTION_FAILS:
          with patch('''requests.Session.send''' ,						_lowerCamelCase						):
               yield
     elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
          # inspired from https://stackoverflow.com/a/904609
          with patch('''requests.Session.request''' ,						_lowerCamelCase						):
               yield
     elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
          with patch('''datasets.config.HF_DATASETS_OFFLINE''' ,						_lowerCamelCase						):
               yield
     else:
          raise ValueError('''Please use a value from the OfflineSimulationMode enum.'''						)







@contextmanager
def       _UpperCamelCase			(*_lowerCamelCase				:  Union[str, Any] ,						**_lowerCamelCase				:  List[str]						)-> Any:




     '''simple docstring'''





     __snake_case            =	str(Path().resolve()						)
     with tempfile.TemporaryDirectory(*_lowerCamelCase ,						**_lowerCamelCase						) as tmp_dir:
          try:
               os.chdir(_lowerCamelCase						)
               yield
          finally:
               os.chdir(_lowerCamelCase						)







@contextmanager
def       _UpperCamelCase			()-> Optional[int]:




     '''simple docstring'''





     import gc

     gc.collect()
     __snake_case            =	pa.total_allocated_bytes()
     yield
     assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."







@contextmanager
def       _UpperCamelCase			()-> List[Any]:




     '''simple docstring'''





     import gc

     gc.collect()
     __snake_case            =	pa.total_allocated_bytes()
     yield
     assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."







def       _UpperCamelCase			(_lowerCamelCase				:  Any ,						_lowerCamelCase				:  int						)-> Any:




     '''simple docstring'''





     return deepcopy(_lowerCamelCase						).integers(0 ,						1_00 ,						10						).tolist() == deepcopy(_lowerCamelCase						).integers(0 ,						1_00 ,						10						).tolist()







def       _UpperCamelCase			(_lowerCamelCase				:  Union[str, Any]						)-> List[Any]:




     '''simple docstring'''





     import decorator
     from requests.exceptions import HTTPError

     def _wrapper(_lowerCamelCase				:  int ,						*_lowerCamelCase				:  int ,						**_lowerCamelCase				:  Optional[int]						):
          try:
               return func(*_lowerCamelCase ,						**_lowerCamelCase						)
          except HTTPError as err:
               if str(_lowerCamelCase						).startswith('''500'''						) or str(_lowerCamelCase						).startswith('''502'''						):
                    pytest.xfail(str(_lowerCamelCase						)						)
               raise err

     return decorator.decorator(_wrapper ,						_lowerCamelCase						)





class      lowerCAmelCase :


       def __init__( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	)   ->	Dict:



            '''simple docstring'''




            __snake_case            =	returncode
            __snake_case            =	stdout
            __snake_case            =	stderr







async def       _UpperCamelCase			(_lowerCamelCase				:  List[str] ,						_lowerCamelCase				:  Union[str, Any]						)-> Dict:




     '''simple docstring'''





     while True:
          __snake_case            =	await stream.readline()
          if line:
               callback(_lowerCamelCase						)
          else:
               break







async def       _UpperCamelCase			(_lowerCamelCase				:  Tuple ,						_lowerCamelCase				:  Optional[int]=None ,						_lowerCamelCase				:  Optional[Any]=None ,						_lowerCamelCase				:  Tuple=None ,						_lowerCamelCase				:  Dict=False ,						_lowerCamelCase				:  List[Any]=False						)-> _RunOutput:




     '''simple docstring'''





     if echo:
          print('''\nRunning: ''' ,						''' '''.join(_lowerCamelCase						)						)

     __snake_case            =	await asyncio.create_subprocess_exec(
         cmd[0] ,						*cmd[1:] ,						stdin=_lowerCamelCase ,						stdout=asyncio.subprocess.PIPE ,						stderr=asyncio.subprocess.PIPE ,						env=_lowerCamelCase ,						)

     # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
     # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
     #
     # If it starts hanging, will need to switch to the following code. The problem is that no data
     # will be seen until it's done and if it hangs for example there will be no debug info.
     # out, err = await p.communicate()
     # return _RunOutput(p.returncode, out, err)

     __snake_case            =	[]
     __snake_case            =	[]

     def tee(_lowerCamelCase				:  int ,						_lowerCamelCase				:  List[Any] ,						_lowerCamelCase				:  str ,						_lowerCamelCase				:  Dict=""						):
          __snake_case            =	line.decode('''utf-8'''						).rstrip()
          sink.append(_lowerCamelCase						)
          if not quiet:
               print(_lowerCamelCase ,						_lowerCamelCase ,						file=_lowerCamelCase						)

    # XXX: the timeout doesn't seem to make any difference here
     await asyncio.wait(
         [
             _read_stream(p.stdout ,						lambda _lowerCamelCase						: tee(_lowerCamelCase ,						_lowerCamelCase ,						sys.stdout ,						label='''stdout:'''						)						),
             _read_stream(p.stderr ,						lambda _lowerCamelCase						: tee(_lowerCamelCase ,						_lowerCamelCase ,						sys.stderr ,						label='''stderr:'''						)						),
         ] ,						timeout=_lowerCamelCase ,						)
     return _RunOutput(await p.wait() ,						_lowerCamelCase ,						_lowerCamelCase						)







def       _UpperCamelCase			(_lowerCamelCase				:  Optional[Any] ,						_lowerCamelCase				:  Any=None ,						_lowerCamelCase				:  List[str]=None ,						_lowerCamelCase				:  Optional[Any]=1_80 ,						_lowerCamelCase				:  Dict=False ,						_lowerCamelCase				:  int=True						)-> _RunOutput:




     '''simple docstring'''





     __snake_case            =	asyncio.get_event_loop()
     __snake_case            =	loop.run_until_complete(
         _stream_subprocess(_lowerCamelCase ,						env=_lowerCamelCase ,						stdin=_lowerCamelCase ,						timeout=_lowerCamelCase ,						quiet=_lowerCamelCase ,						echo=_lowerCamelCase						)						)

     __snake_case            =	''' '''.join(_lowerCamelCase						)
     if result.returncode > 0:
          __snake_case            =	'''\n'''.join(result.stderr						)
          raise RuntimeError(
              f'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
              f'''The combined stderr from workers follows:\n{stderr}'''						)

     # check that the subprocess actually did run and produced some output, should the test rely on
     # the remote side to do the testing
     if not result.stdout and not result.stderr:
          raise RuntimeError(f'''\'{cmd_str}\' produced no output.'''						)

     return result







def       _UpperCamelCase			()-> Dict:




     '''simple docstring'''





     __snake_case            =	os.environ.get('''PYTEST_XDIST_WORKER''' ,						'''gw0'''						)
     __snake_case            =	re.sub(R'''^gw''' ,						'''''' ,						_lowerCamelCase ,						0 ,						re.M						)
     return int(_lowerCamelCase						)







def       _UpperCamelCase			()-> Tuple:




     '''simple docstring'''





     __snake_case            =	2_95_00
     __snake_case            =	pytest_xdist_worker_id()
     return port + uniq_delta






