



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  __snake_case      :







							'''simple docstring'''






							def __init__(							self  ,  a_  ,  a_=2  ,  a_=True  ,  a_=False  ,  a_=10  ,  a_=3  ,  a_=32 * 4  ,  a_=32 * 6  ,  a_=4  ,  a_=32  ,  ):
											a__				      =		parent
											a__				      =		batch_size
											a__				      =		is_training
											a__				      =		use_auxiliary_loss
											a__				      =		num_queries
											a__				      =		num_channels
											a__				      =		min_size
											a__				      =		max_size
											a__				      =		num_labels
											a__				      =		mask_feature_size


							def _a      (							self		):
											a__				      =		floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]		).to(
											    __a		)

											a__				      =		torch.ones([self.batch_size, self.min_size, self.max_size]  ,  device=__a		)

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

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


							def _a      (							self		):
											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 _a      (							self		):
											a__      ,			a__      ,			a__      ,			a__      ,			a__				      =		self.prepare_config_and_inputs()
											a__				      =		{"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
											return config, inputs_dict


							def _a      (							self  ,  a_  ,  a_		):
											a__				      =		output.encoder_hidden_states
											a__				      =		output.pixel_decoder_hidden_states
											a__				      =		output.transformer_decoder_hidden_states

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


							def _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_=False		):
											with torch.no_grad():
															a__				      =		MaskFormerModel(config=__a		)
															model.to(__a		)
															model.eval()

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



							def _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											a__				      =		MaskFormerForInstanceSegmentation(config=__a		)
											model.to(__a		)
											model.eval()

											def comm_check_on_output(a_		):
															# 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():
															a__				      =		model(pixel_values=__a  ,  pixel_mask=__a		)
															a__				      =		model(__a		)

															comm_check_on_output(__a		)

															a__				      =		model(
															    pixel_values=__a  ,  pixel_mask=__a  ,  mask_labels=__a  ,  class_labels=__a		)

											comm_check_on_output(__a		)

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




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







							'''simple docstring'''






							UpperCamelCase__				:      Any         =					(MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
							UpperCamelCase__				:      Optional[int]         =					(
							    {"""feature-extraction""": MaskFormerModel, """image-segmentation""": MaskFormerForInstanceSegmentation}
							    if is_torch_available()
							    else {}
							)

							UpperCamelCase__				:      List[str]         =					False
							UpperCamelCase__				:      List[str]         =					False
							UpperCamelCase__				:      str         =					False
							UpperCamelCase__				:      List[Any]         =					False


							def _a      (							self		):
											a__				      =		MaskFormerModelTester(self		)
											a__				      =		ConfigTester(self  ,  config_class=__a  ,  has_text_modality=__a		)


							def _a      (							self		):
											self.config_tester.run_common_tests()


							def _a      (							self		):
											a__      ,			a__				      =		self.model_tester.prepare_config_and_inputs_for_common()
											self.model_tester.create_and_check_maskformer_model(__a  ,  **__a  ,  output_hidden_states=__a		)


							def _a      (							self		):
											a__				      =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__a		)


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


							@unittest.skip(reason="""MaskFormer does not have a get_input_embeddings method"""		)
							def _a      (							self		):
											pass


							@unittest.skip(reason="""MaskFormer is not a generative model"""		)
							def _a      (							self		):
											pass


							@unittest.skip(reason="""MaskFormer does not use token embeddings"""		)
							def _a      (							self		):
											pass


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


							@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""		)
							def _a      (							self		):
											pass


							def _a      (							self		):
											a__      ,			a__				      =		self.model_tester.prepare_config_and_inputs_for_common()

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

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


							@slow
							def _a      (							self		):
											for model_name in ["facebook/maskformer-swin-small-coco"]:
															a__				      =		MaskFormerModel.from_pretrained(__a		)
															self.assertIsNotNone(__a		)


							def _a      (							self		):
											a__				      =		(self.model_tester.min_size,) * 2
											a__				      =		{
											    """pixel_values""": torch.randn((2, 3, *size)  ,  device=__a		),
											    """mask_labels""": torch.randn((2, 10, *size)  ,  device=__a		),
											    """class_labels""": torch.zeros(2  ,  10  ,  device=__a		).long(),
											}

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


							def _a      (							self		):
											a__      ,			a__				      =		self.model_tester.prepare_config_and_inputs_for_common()
											self.model_tester.create_and_check_maskformer_model(__a  ,  **__a  ,  output_hidden_states=__a		)


							def _a      (							self		):
											a__      ,			a__				      =		self.model_tester.prepare_config_and_inputs_for_common()

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


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

											a__				      =		model_class(__a		)
											model.to(__a		)
											model.train()

											a__				      =		model(__a  ,  mask_labels=__a  ,  class_labels=__a		).loss
											loss.backward()



							def _a      (							self		):
											a__				      =		self.all_model_classes[1]
											a__      ,			a__      ,			a__      ,			a__      ,			a__				      =		self.model_tester.prepare_config_and_inputs()
											a__				      =		True
											a__				      =		True

											a__				      =		model_class(__a		)
											model.to(__a		)
											model.train()

											a__				      =		model(__a  ,  mask_labels=__a  ,  class_labels=__a		)

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

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

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

											outputs.loss.backward(retain_graph=__a		)

											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							 =					1E-4

def 			A_      (	):

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




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







							'''simple docstring'''






							@cached_property
							def _a      (							self		):
											return (
											    MaskFormerImageProcessor.from_pretrained("""facebook/maskformer-swin-small-coco"""		)
											    if is_vision_available()
											    else None
											)


							def _a      (							self		):
											a__				      =		MaskFormerModel.from_pretrained("""facebook/maskformer-swin-small-coco"""		).to(__a		)
											a__				      =		self.default_image_processor
											a__				      =		prepare_img()
											a__				      =		image_processor(__a  ,  return_tensors="""pt"""		).to(__a		)
											a__				      =		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(__a  ,  (1, 3, 800, 1_088)		)

											with torch.no_grad():
															a__				      =		model(**__a		)

											a__				      =		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(__a		)
											self.assertTrue(
											    torch.allclose(
											        outputs.encoder_last_hidden_state[0, 0, :3, :3]  ,  __a  ,  atol=__a		)		)

											a__				      =		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(__a		)
											self.assertTrue(
											    torch.allclose(
											        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]  ,  __a  ,  atol=__a		)		)

											a__				      =		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(__a		)
											self.assertTrue(
											    torch.allclose(
											        outputs.transformer_decoder_last_hidden_state[0, :3, :3]  ,  __a  ,  atol=__a		)		)


							def _a      (							self		):
											a__				      =		(
											    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco"""		)
											    .to(__a		)
											    .eval()
											)
											a__				      =		self.default_image_processor
											a__				      =		prepare_img()
											a__				      =		image_processor(__a  ,  return_tensors="""pt"""		).to(__a		)
											a__				      =		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(__a  ,  (1, 3, 800, 1_088)		)

											with torch.no_grad():
															a__				      =		model(**__a		)
											# masks_queries_logits
											a__				      =		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)  ,  )
											a__				      =		[
											    [-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],
											]
											a__				      =		torch.tensor(__a		).to(__a		)
											self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]  ,  __a  ,  atol=__a		)		)
											# class_queries_logits
											a__				      =		outputs.class_queries_logits
											self.assertEqual(
											    class_queries_logits.shape  ,  (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)		)
											a__				      =		torch.tensor(
											    [
											        [1.6_5_1_2E0_0, -5.2_5_7_2E0_0, -3.3_5_1_9E0_0],
											        [3.6_1_6_9E-0_2, -5.9_0_2_5E0_0, -2.9_3_1_3E0_0],
											        [1.0_7_6_6E-0_4, -7.7_6_3_0E0_0, -5.1_2_6_3E0_0],
											    ]		).to(__a		)
											self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]  ,  __a  ,  atol=__a		)		)


							def _a      (							self		):
											a__				      =		(
											    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-resnet101-coco-stuff"""		)
											    .to(__a		)
											    .eval()
											)
											a__				      =		self.default_image_processor
											a__				      =		prepare_img()
											a__				      =		image_processor(__a  ,  return_tensors="""pt"""		).to(__a		)
											a__				      =		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(__a  ,  (1, 3, 800, 1_088)		)

											with torch.no_grad():
															a__				      =		model(**__a		)
											# masks_queries_logits
											a__				      =		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)  ,  )
											a__				      =		[[-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]]
											a__				      =		torch.tensor(__a		).to(__a		)
											self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]  ,  __a  ,  atol=__a		)		)
											# class_queries_logits
											a__				      =		outputs.class_queries_logits
											self.assertEqual(
											    class_queries_logits.shape  ,  (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)		)
											a__				      =		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(__a		)
											self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]  ,  __a  ,  atol=__a		)		)



							def _a      (							self		):
											a__				      =		(
											    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco"""		)
											    .to(__a		)
											    .eval()
											)
											a__				      =		self.default_image_processor

											a__				      =		image_processor(
											    [np.zeros((3, 800, 1_333)		), np.zeros((3, 800, 1_333)		)]  ,  segmentation_maps=[np.zeros((384, 384)		).astype(np.floataa		), np.zeros((384, 384)		).astype(np.floataa		)]  ,  return_tensors="""pt"""  ,  )

											a__				      =		inputs["""pixel_values"""].to(__a		)
											a__				      =		[el.to(__a		) for el in inputs["""mask_labels"""]]
											a__				      =		[el.to(__a		) for el in inputs["""class_labels"""]]

											with torch.no_grad():
															a__				      =		model(**__a		)

											self.assertTrue(outputs.loss is not None		)






from math import sqrt

import numpy as np
from sympy import symbols

# Coefficient
# Speed of light (m/s)
UpperCAmelCase							 =					299_792_458

# Symbols
UpperCAmelCase ,       UpperCAmelCase ,       UpperCAmelCase ,       UpperCAmelCase							 =					symbols("""ct x y z""")

def 			A_      (	__a     :				float		):

				"""simple docstring"""
				if velocity > c:
								raise ValueError("""Speed must not exceed light speed 299,792,458 [m/s]!"""		)
				elif velocity < 1:
								# Usually the speed should be much higher than 1 (c order of magnitude)
								raise ValueError("""Speed must be greater than or equal to 1!"""		)

				return velocity / c

def 			A_      (	__a     :				float		):

				"""simple docstring"""
				return 1 / sqrt(1 - beta(__a		) ** 2		)

def 			A_      (	__a     :				float		):

				"""simple docstring"""
				return np.array(
				    [
				        [gamma(__a		), -gamma(__a		) * beta(__a		), 0, 0],
				        [-gamma(__a		) * beta(__a		), gamma(__a		), 0, 0],
				        [0, 0, 1, 0],
				        [0, 0, 0, 1],
				    ]		)

def 			A_      (	__a     :				float ,		__a     :				np.ndarray | None = None		):

				"""simple docstring"""
				# Ensure event is not empty
				if event is None:
								a__				      =		np.array([ct, x, y, z]		)  # Symbolic four vector
				else:
								event[0] *= c  # x0 is ct (speed of light * time)

				return transformation_matrix(__a		) @ event


if __name__ == "__main__":
	import doctest

	doctest.testmod()

	# Example of symbolic vector:
	UpperCAmelCase							 =					transform(29_979_245)
	print("""Example of four vector: """)
	print(f"""ct' = {four_vector[0]}""")
	print(f"""x' = {four_vector[1]}""")
	print(f"""y' = {four_vector[2]}""")
	print(f"""z' = {four_vector[3]}""")

	# Substitute symbols with numerical values
	UpperCAmelCase							 =					{ct: c, x: 1, y: 1, z: 1}
	UpperCAmelCase							 =					[four_vector[i].subs(sub_dict) for i in range(4)]

	print(f"""\n{numerical_vector}""")

