





"""simple docstring"""






from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
		from transformers import (
		    TFBertModel,
		    TFCLIPVisionModel,
		    TFDeiTModel,
		    TFRobertaModel,
		    TFVisionTextDualEncoderModel,
		    TFViTModel,
		    VisionTextDualEncoderConfig,
		)

if is_vision_available():
		from PIL import Image

		from transformers import VisionTextDualEncoderProcessor

def       __A (     a_  :Optional[Any])						->						str:







				if isinstance(UpperCamelCase__				,    collections.abc.Iterable):
								return x
				return (x, x)




@require_tf
class 			__lowercase     :







					'''simple docstring'''




					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase       ):
									pass







					def 	_lowerCamelCase						(  self       ):
									pass







					def 	_lowerCamelCase						(  self       ):
									pass







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase=None		,     **_UpperCAmelCase       ):
									__a	:  Union[str, Any]         =					VisionTextDualEncoderConfig.from_vision_text_configs(_a		,     _a       )

									__a	:  Optional[Any]         =					TFVisionTextDualEncoderModel(_a       )

									__a	:  int         =					model(input_ids=_a		,     pixel_values=_a		,     attention_mask=_a       )

									self.assertEqual(output['''text_embeds'''].shape		,     (input_ids.shape[0], config.projection_dim)       )
									self.assertEqual(output['''image_embeds'''].shape		,     (pixel_values.shape[0], config.projection_dim)       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase=None		,     **_UpperCAmelCase       ):
									__a    ,  __a	:  str         =					self.get_vision_text_model(_a		,     _a       )
									__a	:  Any         =					TFVisionTextDualEncoderModel(vision_model=_a		,     text_model=_a       )

									__a	:  List[str]         =					model(input_ids=_a		,     pixel_values=_a		,     attention_mask=_a       )

									self.assertEqual(output['''text_embeds'''].shape		,     (input_ids.shape[0], model.config.projection_dim)       )
									self.assertEqual(output['''image_embeds'''].shape		,     (pixel_values.shape[0], model.config.projection_dim)       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase=None		,     **_UpperCAmelCase       ):
									__a    ,  __a	:  Dict         =					self.get_vision_text_model(_a		,     _a       )
									__a	:  Union[str, Any]         =					{'''vision_model''': vision_model, '''text_model''': text_model}
									__a	:  Tuple         =					TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_a       )

									__a	:  Optional[int]         =					model(input_ids=_a		,     pixel_values=_a		,     attention_mask=_a       )

									self.assertEqual(output['''text_embeds'''].shape		,     (input_ids.shape[0], model.config.projection_dim)       )
									self.assertEqual(output['''image_embeds'''].shape		,     (pixel_values.shape[0], model.config.projection_dim)       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase=None		,     **_UpperCAmelCase       ):
									__a    ,  __a	:  Tuple         =					self.get_vision_text_model(_a		,     _a       )
									__a	:  str         =					TFVisionTextDualEncoderModel(vision_model=_a		,     text_model=_a       )

									__a	:  List[str]         =					model(input_ids=_a		,     pixel_values=_a		,     attention_mask=_a       )
									__a	:  Dict         =					output[0].numpy()

									with tempfile.TemporaryDirectory() as tmpdirname:
													model.save_pretrained(_a       )
													__a	:  Dict         =					TFVisionTextDualEncoderModel.from_pretrained(_a       )

													__a	:  Tuple         =					model(input_ids=_a		,     pixel_values=_a		,     attention_mask=_a       )
													__a	:  Optional[int]         =					after_output[0].numpy()
													__a	:  Dict         =					np.amax(np.abs(out_a - out_a       )       )
													self.assertLessEqual(_a		,     1e-5       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase=None		,     **_UpperCAmelCase       ):
									__a    ,  __a	:  str         =					self.get_vision_text_model(_a		,     _a       )
									__a	:  Any         =					TFVisionTextDualEncoderModel(vision_model=_a		,     text_model=_a       )

									__a	:  int         =					model(
									    input_ids=_a		,     pixel_values=_a		,     attention_mask=_a		,     output_attentions=_a       )

									__a	:  Tuple         =					output.vision_model_output.attentions
									self.assertEqual(len(_a       )		,     vision_config.num_hidden_layers       )

									# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
									__a	:  Optional[Any]         =					to_atuple(vision_model.config.image_size       )
									__a	:  Optional[int]         =					to_atuple(vision_model.config.patch_size       )
									__a	:  Optional[Any]         =					(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
									__a	:  int         =					num_patches + 1
									self.assertEqual(vision_attentions[0].shape[-3:]		,     (vision_config.num_attention_heads, seq_len, seq_len)       )

									__a	:  List[str]         =					output.text_model_output.attentions
									self.assertEqual(len(_a       )		,     text_config.num_hidden_layers       )

									self.assertEqual(
									    text_attentions[0].shape[-3:]		,     (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])		,     )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase       ):
									__a	:  Optional[Any]         =					np.abs((a - b)       ).max()
									self.assertLessEqual(_a		,     _a		,     f"""Difference between torch and flax is {diff} (>= {tol})."""       )







					def 	_lowerCamelCase						(  self       ):
									__a	:  Tuple         =					self.prepare_config_and_inputs()
									self.check_vision_text_dual_encoder_model(**_a       )







					def 	_lowerCamelCase						(  self       ):
									__a	:  Any         =					self.prepare_config_and_inputs()
									self.check_model_from_pretrained_configs(**_a       )







					def 	_lowerCamelCase						(  self       ):
									__a	:  Tuple         =					self.prepare_config_and_inputs()
									self.check_vision_text_dual_encoder_from_pretrained(**_a       )







					def 	_lowerCamelCase						(  self       ):
									__a	:  Any         =					self.prepare_config_and_inputs()
									self.check_save_load(**_a       )







					def 	_lowerCamelCase						(  self       ):
									__a	:  str         =					self.prepare_config_and_inputs()
									self.check_vision_text_output_attention(**_a       )







					@slow
					def 	_lowerCamelCase						(  self       ):
									__a    ,  __a	:  Optional[int]         =					self.get_pretrained_model_and_inputs()

									__a	:  str         =					model_a(**_a       )
									__a	:  Dict         =					outputs[0].numpy()

									with tempfile.TemporaryDirectory() as tmp_dirname:
													model_a.save_pretrained(_a       )
													__a	:  Tuple         =					TFVisionTextDualEncoderModel.from_pretrained(_a       )

													__a	:  Union[str, Any]         =					model_a(**_a       )
													__a	:  Any         =					after_outputs[0].numpy()
													__a	:  Tuple         =					np.amax(np.abs(out_a - out_a       )       )
													self.assertLessEqual(_a		,     1e-5       )






@require_tf
class 			__lowercase     (     _UpperCamelCase				, unittest.TestCase							):







					'''simple docstring'''




					def 	_lowerCamelCase						(  self       ):
									__a	:  str         =					TFVisionTextDualEncoderModel.from_vision_text_pretrained(
									    '''hf-internal-testing/tiny-random-vit'''		,     '''hf-internal-testing/tiny-random-bert'''       )
									__a	:  int         =					13
									__a	:  List[str]         =					floats_tensor(
									    [
									        batch_size,
									        model.vision_model.config.num_channels,
									        model.vision_model.config.image_size,
									        model.vision_model.config.image_size,
									    ]       )
									__a	:  Tuple         =					ids_tensor([batch_size, 4]		,     model.text_model.config.vocab_size       )
									__a	:  List[str]         =					random_attention_mask([batch_size, 4]       )
									__a	:  List[str]         =					{'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

									return model, inputs







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase       ):
									__a	:  List[Any]         =					TFViTModel(_a		,     name='''vision_model'''       )
									__a	:  str         =					TFBertModel(_a		,     name='''text_model'''       )
									return vision_model, text_model







					def 	_lowerCamelCase						(  self       ):
									__a	:  str         =					TFViTModelTester(self       )
									__a	:  Dict         =					TFBertModelTester(self       )
									__a	:  Union[str, Any]         =					vit_model_tester.prepare_config_and_inputs()
									__a	:  Optional[int]         =					bert_model_tester.prepare_config_and_inputs()

									__a    ,  __a    ,  __a	:  Any         =					vision_config_and_inputs

									(
									    (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  				
									)	:  List[str]         =					text_config_and_inputs

									return {
									    "text_config": text_config,
									    "vision_config": vision_config,
									    "pixel_values": pixel_values,
									    "attention_mask": input_mask,
									    "input_ids": input_ids,
									    "text_token_type_ids": token_type_ids,
									    "text_sequence_labels": sequence_labels,
									    "text_token_labels": token_labels,
									    "text_choice_labels": choice_labels,
									}






@require_tf
class 			__lowercase     (     _UpperCamelCase				, unittest.TestCase							):







					'''simple docstring'''




					def 	_lowerCamelCase						(  self       ):
									# DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
									# just reinitialize it.
									__a	:  Any         =					TFVisionTextDualEncoderModel.from_vision_text_pretrained(
									    '''Rocketknight1/tiny-random-deit-tf'''		,     '''hf-internal-testing/tiny-random-roberta'''       )
									__a	:  Union[str, Any]         =					13
									__a	:  Dict         =					floats_tensor(
									    [
									        batch_size,
									        model.vision_model.config.num_channels,
									        model.vision_model.config.image_size,
									        model.vision_model.config.image_size,
									    ]       )
									__a	:  Union[str, Any]         =					ids_tensor([batch_size, 4]		,     model.text_model.config.vocab_size       )
									__a	:  int         =					random_attention_mask([batch_size, 4]       )
									__a	:  Optional[int]         =					{'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

									return model, inputs







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase=None		,     **_UpperCAmelCase       ):
									__a    ,  __a	:  int         =					self.get_vision_text_model(_a		,     _a       )
									__a	:  List[str]         =					TFVisionTextDualEncoderModel(vision_model=_a		,     text_model=_a       )

									__a	:  List[Any]         =					model(
									    input_ids=_a		,     pixel_values=_a		,     attention_mask=_a		,     output_attentions=_a       )

									__a	:  Tuple         =					output.vision_model_output.attentions
									self.assertEqual(len(_a       )		,     vision_config.num_hidden_layers       )

									# in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
									__a	:  Dict         =					to_atuple(vision_model.config.image_size       )
									__a	:  str         =					to_atuple(vision_model.config.patch_size       )
									__a	:  Dict         =					(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
									__a	:  List[Any]         =					num_patches + 2
									self.assertEqual(vision_attentions[0].shape[-3:]		,     (vision_config.num_attention_heads, seq_len, seq_len)       )

									__a	:  List[Any]         =					output.text_model_output.attentions
									self.assertEqual(len(_a       )		,     text_config.num_hidden_layers       )

									self.assertEqual(
									    text_attentions[0].shape[-3:]		,     (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])		,     )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase       ):
									__a	:  Tuple         =					TFDeiTModel(_a		,     name='''vision_model'''       )
									__a	:  int         =					TFRobertaModel(_a		,     name='''text_model'''       )
									return vision_model, text_model







					def 	_lowerCamelCase						(  self       ):
									__a	:  Tuple         =					TFDeiTModelTester(self       )
									__a	:  List[Any]         =					TFRobertaModelTester(self       )
									__a	:  Tuple         =					vit_model_tester.prepare_config_and_inputs()
									__a	:  List[str]         =					bert_model_tester.prepare_config_and_inputs()

									__a    ,  __a    ,  __a	:  List[Any]         =					vision_config_and_inputs

									(
									    (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  				
									)	:  Optional[int]         =					text_config_and_inputs

									return {
									    "text_config": text_config,
									    "vision_config": vision_config,
									    "pixel_values": pixel_values,
									    "attention_mask": input_mask,
									    "input_ids": input_ids,
									    "text_token_type_ids": token_type_ids,
									    "text_sequence_labels": sequence_labels,
									    "text_token_labels": token_labels,
									    "text_choice_labels": choice_labels,
									}






@require_tf
class 			__lowercase     (     _UpperCamelCase				, unittest.TestCase							):







					'''simple docstring'''




					def 	_lowerCamelCase						(  self       ):
									__a	:  int         =					TFVisionTextDualEncoderModel.from_vision_text_pretrained(
									    '''Rocketknight1/tiny-random-clip-tf'''		,     '''hf-internal-testing/tiny-random-bert'''       )
									__a	:  Optional[Any]         =					13
									__a	:  Dict         =					floats_tensor(
									    [
									        batch_size,
									        model.vision_model.config.num_channels,
									        model.vision_model.config.image_size,
									        model.vision_model.config.image_size,
									    ]       )
									__a	:  Optional[Any]         =					ids_tensor([batch_size, 4]		,     model.text_model.config.vocab_size       )
									__a	:  Dict         =					random_attention_mask([batch_size, 4]       )
									__a	:  Optional[Any]         =					{'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

									return model, inputs







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase       ):
									__a	:  List[Any]         =					TFCLIPVisionModel(_a		,     name='''vision_model'''       )
									__a	:  Union[str, Any]         =					TFBertModel(_a		,     name='''text_model'''       )
									return vision_model, text_model







					def 	_lowerCamelCase						(  self       ):
									__a	:  List[Any]         =					TFCLIPVisionModelTester(self       )
									__a	:  Dict         =					TFBertModelTester(self       )
									__a	:  Optional[Any]         =					clip_model_tester.prepare_config_and_inputs()
									__a	:  Tuple         =					bert_model_tester.prepare_config_and_inputs()

									__a    ,  __a	:  Union[str, Any]         =					vision_config_and_inputs

									(
									    (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  (
									    __a				
									)    ,  				
									)	:  str         =					text_config_and_inputs

									return {
									    "text_config": text_config,
									    "vision_config": vision_config,
									    "pixel_values": pixel_values,
									    "attention_mask": input_mask,
									    "input_ids": input_ids,
									    "text_token_type_ids": token_type_ids,
									    "text_sequence_labels": sequence_labels,
									    "text_token_labels": token_labels,
									    "text_choice_labels": choice_labels,
									}






@require_vision
@require_tf
class 			__lowercase     (     unittest.TestCase							):







					'''simple docstring'''




					@slow
					def 	_lowerCamelCase						(  self       ):
									__a	:  Optional[Any]         =					TFVisionTextDualEncoderModel.from_pretrained(
									    '''clip-italian/clip-italian'''		,     logit_scale_init_value=1.0		,     from_pt=_a       )
									__a	:  int         =					VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian'''       )

									__a	:  Any         =					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
									__a	:  Any         =					processor(
									    text=['''una foto di un gatto''', '''una foto di un cane''']		,     images=_a		,     padding=_a		,     return_tensors='''np'''       )

									__a	:  List[str]         =					model(**_a       )

									# verify the logits
									self.assertEqual(outputs.logits_per_image.shape		,     (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])       )
									self.assertEqual(
									    outputs.logits_per_text.shape		,     (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])		,     )

									__a	:  Any         =					np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]]       )

									self.assertTrue(np.allclose(outputs.logits_per_image.numpy()		,     _a		,     atol=1e-3       )       )






"""simple docstring"""






import argparse
import re

import numpy as np
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import (
    SamConfig,
    SamImageProcessor,
    SamModel,
    SamProcessor,
    SamVisionConfig,
)


A	     =					{
    '''iou_prediction_head.layers.0''': '''iou_prediction_head.proj_in''',
    '''iou_prediction_head.layers.1''': '''iou_prediction_head.layers.0''',
    '''iou_prediction_head.layers.2''': '''iou_prediction_head.proj_out''',
    '''mask_decoder.output_upscaling.0''': '''mask_decoder.upscale_conv1''',
    '''mask_decoder.output_upscaling.1''': '''mask_decoder.upscale_layer_norm''',
    '''mask_decoder.output_upscaling.3''': '''mask_decoder.upscale_conv2''',
    '''mask_downscaling.0''': '''mask_embed.conv1''',
    '''mask_downscaling.1''': '''mask_embed.layer_norm1''',
    '''mask_downscaling.3''': '''mask_embed.conv2''',
    '''mask_downscaling.4''': '''mask_embed.layer_norm2''',
    '''mask_downscaling.6''': '''mask_embed.conv3''',
    '''point_embeddings''': '''point_embed''',
    '''pe_layer.positional_encoding_gaussian_matrix''': '''shared_embedding.positional_embedding''',
    '''image_encoder''': '''vision_encoder''',
    '''neck.0''': '''neck.conv1''',
    '''neck.1''': '''neck.layer_norm1''',
    '''neck.2''': '''neck.conv2''',
    '''neck.3''': '''neck.layer_norm2''',
    '''patch_embed.proj''': '''patch_embed.projection''',
    '''.norm''': '''.layer_norm''',
    '''blocks''': '''layers''',
}

def       __A (     a_  :List[Any])						->						List[Any]:
				__a	:  List[Any]         =					{}
				state_dict.pop('''pixel_mean'''				,    a_)
				state_dict.pop('''pixel_std'''				,    a_)

				__a	:  List[Any]         =					R'''.*.output_hypernetworks_mlps.(\d+).layers.(\d+).*'''

				for key, value in state_dict.items():
								for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
												if key_to_modify in key:
																__a	:  int         =					key.replace(a_				,    a_)

								if re.match(a_				,    a_):
												__a	:  Optional[Any]         =					int(re.match(a_				,    a_).group(2))
												if layer_nb == 0:
																__a	:  Any         =					key.replace('''layers.0'''				,    '''proj_in''')
												elif layer_nb == 1:
																__a	:  Dict         =					key.replace('''layers.1'''				,    '''layers.0''')
												elif layer_nb == 2:
																__a	:  Optional[int]         =					key.replace('''layers.2'''				,    '''proj_out''')

								__a	:  int         =					value

				__a	:  Union[str, Any]         =					model_state_dict[
				    '''prompt_encoder.shared_embedding.positional_embedding'''
				]

				return model_state_dict

def       __A (     a_  :Optional[int]				,    a_  :Optional[Any]				,    a_  :Dict				,    a_  :Optional[int]="ybelkada/segment-anything")						->						Dict:
				__a	:  Dict         =					hf_hub_download(a_				,    F"""checkpoints/{model_name}.pth""")

				if "sam_vit_b" in model_name:
								__a	:  List[str]         =					SamConfig()
				elif "sam_vit_l" in model_name:
								__a	:  List[Any]         =					SamVisionConfig(
								    hidden_size=10_24				,    num_hidden_layers=24				,    num_attention_heads=16				,    global_attn_indexes=[5, 11, 17, 23]				,    )

								__a	:  List[Any]         =					SamConfig(
								    vision_config=a_				,    )
				elif "sam_vit_h" in model_name:
								__a	:  List[str]         =					SamVisionConfig(
								    hidden_size=12_80				,    num_hidden_layers=32				,    num_attention_heads=16				,    global_attn_indexes=[7, 15, 23, 31]				,    )

								__a	:  Optional[int]         =					SamConfig(
								    vision_config=a_				,    )

				__a	:  int         =					torch.load(a_				,    map_location='''cpu''')
				__a	:  Tuple         =					replace_keys(a_)

				__a	:  Optional[int]         =					SamImageProcessor()

				__a	:  Any         =					SamProcessor(image_processor=a_)
				__a	:  Any         =					SamModel(a_)

				hf_model.load_state_dict(a_)
				__a	:  Dict         =					hf_model.to('''cuda''')

				__a	:  Tuple         =					'''https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png'''
				__a	:  str         =					Image.open(requests.get(a_				,    stream=a_).raw).convert('''RGB''')

				__a	:  Tuple         =					[[[4_00, 6_50]]]
				__a	:  Tuple         =					[[1]]

				__a	:  Tuple         =					processor(images=np.array(a_)				,    return_tensors='''pt''').to('''cuda''')

				with torch.no_grad():
								__a	:  str         =					hf_model(**a_)
				__a	:  Optional[int]         =					output.iou_scores.squeeze()

				if model_name == "sam_vit_h_4b8939":
								assert scores[-1].item() == 0.5_7_9_8_9_0_2_5_1_1_5_9_6_6_8

								__a	:  Any         =					processor(
								    images=np.array(a_)				,    input_points=a_				,    input_labels=a_				,    return_tensors='''pt''').to('''cuda''')

								with torch.no_grad():
												__a	:  Optional[int]         =					hf_model(**a_)
								__a	:  Optional[int]         =					output.iou_scores.squeeze()

								assert scores[-1].item() == 0.9_7_1_2_6_0_3_0_9_2_1_9_3_6_0_4

								__a	:  str         =					((75, 2_75, 17_25, 8_50),)

								__a	:  List[str]         =					processor(images=np.array(a_)				,    input_boxes=a_				,    return_tensors='''pt''').to('''cuda''')

								with torch.no_grad():
												__a	:  Any         =					hf_model(**a_)
								__a	:  Any         =					output.iou_scores.squeeze()

								assert scores[-1].item() == 0.8_6_8_6_0_1_5_6_0_5_9_2_6_5_1_4

								# Test with 2 points and 1 image.
								__a	:  int         =					[[[4_00, 6_50], [8_00, 6_50]]]
								__a	:  Dict         =					[[1, 1]]

								__a	:  Optional[Any]         =					processor(
								    images=np.array(a_)				,    input_points=a_				,    input_labels=a_				,    return_tensors='''pt''').to('''cuda''')

								with torch.no_grad():
												__a	:  int         =					hf_model(**a_)
								__a	:  Any         =					output.iou_scores.squeeze()

								assert scores[-1].item() == 0.9_9_3_6_0_4_7_7_9_2_4_3_4_6_9_2


if __name__ == "__main__":
		A	     =					argparse.ArgumentParser()
		A	     =					['''sam_vit_b_01ec64''', '''sam_vit_h_4b8939''', '''sam_vit_l_0b3195''']
		parser.add_argument(
		    '''--model_name''',
		    default='''sam_vit_h_4b8939''',
		    choices=choices,
		    type=str,
		    help='''Path to hf config.json of model to convert''',
		)
		parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
		parser.add_argument(
		    '''--push_to_hub''',
		    action='''store_true''',
		    help='''Whether to push the model and processor to the hub after converting''',
		)
		parser.add_argument(
		    '''--model_hub_id''',
		    default='''ybelkada/segment-anything''',
		    choices=choices,
		    type=str,
		    help='''Path to hf config.json of model to convert''',
		)

		A	     =					parser.parse_args()

		convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)