



"""simple docstring"""
import os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


__a           =							namedtuple("ExampleNamedTuple", "a b c")
class 							lowerCamelCase    (     unittest.TestCase							):






					'''simple docstring'''





					def   lowerCAmelCase_							(			self:				Dict		)  ->      Any:
											snake_case_					:Tuple		=     torch.randn(5		,	2		)
											snake_case_					:Dict		=     torch.device("""cuda"""		) if torch.cuda.is_available() else torch.device("""cpu"""		)

											snake_case_					:Tuple		=     send_to_device(snake_case		,	snake_case		)
											self.assertTrue(torch.equal(resulta.cpu()		,	snake_case		)		)

											snake_case_					:List[str]		=     send_to_device((tensor, [tensor, tensor], 1)		,	snake_case		)
											self.assertIsInstance(snake_case		,	snake_case		)
											self.assertTrue(torch.equal(resulta[0].cpu()		,	snake_case		)		)
											self.assertIsInstance(resulta[1]		,	snake_case		)
											self.assertTrue(torch.equal(resulta[1][0].cpu()		,	snake_case		)		)
											self.assertTrue(torch.equal(resulta[1][1].cpu()		,	snake_case		)		)
											self.assertEqual(resulta[2]		,	1		)

											snake_case_					:List[str]		=     send_to_device({"""a""": tensor, """b""": [tensor, tensor], """c""": 1}		,	snake_case		)
											self.assertIsInstance(snake_case		,	snake_case		)
											self.assertTrue(torch.equal(resulta["""a"""].cpu()		,	snake_case		)		)
											self.assertIsInstance(resulta["""b"""]		,	snake_case		)
											self.assertTrue(torch.equal(resulta["""b"""][0].cpu()		,	snake_case		)		)
											self.assertTrue(torch.equal(resulta["""b"""][1].cpu()		,	snake_case		)		)
											self.assertEqual(resulta["""c"""]		,	1		)

											snake_case_					:Optional[int]		=     send_to_device(ExampleNamedTuple(a=snake_case		,	b=[tensor, tensor]		,	c=1		)		,	snake_case		)
											self.assertIsInstance(snake_case		,	snake_case		)
											self.assertTrue(torch.equal(resulta.a.cpu()		,	snake_case		)		)
											self.assertIsInstance(resulta.b		,	snake_case		)
											self.assertTrue(torch.equal(resulta.b[0].cpu()		,	snake_case		)		)
											self.assertTrue(torch.equal(resulta.b[1].cpu()		,	snake_case		)		)
											self.assertEqual(resulta.c		,	1		)

											snake_case_					:Optional[Any]		=     send_to_device(UserDict({"""a""": tensor, """b""": [tensor, tensor], """c""": 1}		)		,	snake_case		)
											self.assertIsInstance(snake_case		,	snake_case		)
											self.assertTrue(torch.equal(resulta["""a"""].cpu()		,	snake_case		)		)
											self.assertIsInstance(resulta["""b"""]		,	snake_case		)
											self.assertTrue(torch.equal(resulta["""b"""][0].cpu()		,	snake_case		)		)
											self.assertTrue(torch.equal(resulta["""b"""][1].cpu()		,	snake_case		)		)
											self.assertEqual(resulta["""c"""]		,	1		)






					def   lowerCAmelCase_							(			self:				Any		)  ->      Optional[int]:
											with self.assertRaises(snake_case		) as cm:
																	snake_case_					:int		=     recursively_apply(torch.tensor		,	(torch.tensor(1		), 1)		,	error_on_other_type=snake_case		)
											self.assertEqual(
											    str(cm.exception		)		,	"""Unsupported types (<class 'int'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed."""		,	)






					def   lowerCAmelCase_							(			self:				str		)  ->      int:
											snake_case_					:Tuple		=     torch.tensor([1, 2, 3, 4, 5]		)
											self.assertEqual(listify(snake_case		)		,	[1, 2, 3, 4, 5]		)

											snake_case_					:int		=     torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]		)
											self.assertEqual(listify(snake_case		)		,	[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]		)

											snake_case_					:Any		=     torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]		)
											self.assertEqual(
											    listify(snake_case		)		,	[[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]		)






					def   lowerCAmelCase_							(			self:				Dict		)  ->      List[Any]:
											with patch_environment(aa=1		,	BB=2		):
																	self.assertEqual(os.environ.get("""AA"""		)		,	"""1"""		)
																	self.assertEqual(os.environ.get("""BB"""		)		,	"""2"""		)

											self.assertNotIn("""AA"""		,	os.environ		)
											self.assertNotIn("""BB"""		,	os.environ		)






					def   lowerCAmelCase_							(			self:				Optional[Any]		)  ->      List[Any]:
											snake_case_					:Any		=     RegressionModel()
											snake_case_					:Union[str, Any]		=     model.forward
											snake_case_					:int		=     convert_outputs_to_fpaa(model.forward		)
											snake_case_					:Optional[int]		=     extract_model_from_parallel(snake_case		,	keep_fpaa_wrapper=snake_case		)
											snake_case_					:str		=     pickle.dumps(snake_case		)






					@require_cuda
					def   lowerCAmelCase_							(			self:				Tuple		)  ->      str:
											snake_case_					:Union[str, Any]		=     RegressionModel()
											snake_case_					:Optional[Any]		=     model.forward
											snake_case_					:Tuple		=     torch.cuda.amp.autocast(dtype=torch.floataa		)(model.forward		)
											snake_case_					:Any		=     convert_outputs_to_fpaa(model.forward		)
											snake_case_					:List[str]		=     extract_model_from_parallel(snake_case		,	keep_fpaa_wrapper=snake_case		)
											snake_case_					:int		=     pickle.dumps(snake_case		)






					@require_cuda
					@require_torch_min_version(version="""2.0"""		)
					def   lowerCAmelCase_							(			self:				Union[str, Any]		)  ->      List[str]:
											snake_case_					:Tuple		=     RegressionModel()
											snake_case_					:Any		=     model.forward
											snake_case_					:Optional[Any]		=     torch.cuda.amp.autocast(dtype=torch.floataa		)(model.forward		)
											snake_case_					:str		=     convert_outputs_to_fpaa(model.forward		)
											snake_case_					:str		=     torch.compile(model.forward		,	backend="""inductor"""		)
											snake_case_					:Tuple		=     torch.randn(4		,	10		).cuda()
											snake_case_					:List[Any]		=     model(snake_case		)






					def   lowerCAmelCase_							(			self:				Any		)  ->      List[str]:
											snake_case_					:Optional[int]		=     RegressionModel()
											# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
											snake_case_					:int		=     torch.nn.parallel.DataParallel(snake_case		)
											snake_case_					:str		=     extract_model_from_parallel(snake_case		)

											self.assertEqual(snake_case		,	snake_case		)






					@require_torch_min_version(version="""2.0"""		)
					def   lowerCAmelCase_							(			self:				Dict		)  ->      Tuple:
											snake_case_					:Tuple		=     RegressionModel()
											snake_case_					:Optional[Any]		=     torch.compile(snake_case		)

											# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
											snake_case_					:Dict		=     torch.nn.parallel.DataParallel(snake_case		)
											snake_case_					:int		=     torch.compile(snake_case		)
											snake_case_					:List[Any]		=     extract_model_from_parallel(snake_case		)

											self.assertEqual(compiled_model._orig_mod		,	compiled_model_unwrapped._orig_mod		)






					def   lowerCAmelCase_							(			self:				Union[str, Any]		)  ->      List[Any]:
											self.assertEqual(find_device([1, """a""", torch.tensor([1, 2, 3]		)]		)		,	torch.device("""cpu"""		)		)
											self.assertEqual(find_device({"""a""": 1, """b""": torch.tensor([1, 2, 3]		)}		)		,	torch.device("""cpu"""		)		)
											self.assertIsNone(find_device([1, """a"""]		)		)








"""simple docstring"""

import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase           =							logging.get_logger(__name__)

lowercase           =							{
    '''facebook/sam-vit-huge''': '''https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json''',
    '''facebook/sam-vit-large''': '''https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json''',
    '''facebook/sam-vit-base''': '''https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json''',
}

class     A_				(   snake_case_	):







				def __init__(				self				:    List[Any]    ,     __lowerCamelCase				:    str=2_5_6    ,     __lowerCamelCase				:    str=1_0_2_4    ,     __lowerCamelCase				:    Optional[Any]=1_6    ,     __lowerCamelCase				:    Union[str, Any]=1_6    ,     __lowerCamelCase				:    str=4    ,     __lowerCamelCase				:    Union[str, Any]="gelu"    ,     __lowerCamelCase				:    Optional[int]=1e-6    ,     **__lowerCamelCase				:    str    ,     )					->       List[Any]:
										super().__init__(**__lowerCamelCase						)
										__magic_name__      =  hidden_size
										__magic_name__      =  image_size
										__magic_name__      =  patch_size
										__magic_name__      =  image_size // patch_size
										__magic_name__      =  mask_input_channels
										__magic_name__      =  num_point_embeddings
										__magic_name__      =  hidden_act
										__magic_name__      =  layer_norm_eps





class     A_				(   snake_case_	):







				def __init__(				self				:    List[str]    ,     __lowerCamelCase				:    Optional[Any]=2_5_6    ,     __lowerCamelCase				:    int="relu"    ,     __lowerCamelCase				:    List[str]=2_0_4_8    ,     __lowerCamelCase				:    Optional[Any]=2    ,     __lowerCamelCase				:    Optional[Any]=8    ,     __lowerCamelCase				:    Optional[Any]=2    ,     __lowerCamelCase				:    Dict=3    ,     __lowerCamelCase				:    Optional[int]=3    ,     __lowerCamelCase				:    Tuple=2_5_6    ,     __lowerCamelCase				:    List[str]=1e-6    ,     **__lowerCamelCase				:    Any    ,     )					->       str:
										super().__init__(**__lowerCamelCase						)
										__magic_name__      =  hidden_size
										__magic_name__      =  hidden_act
										__magic_name__      =  mlp_dim
										__magic_name__      =  num_hidden_layers
										__magic_name__      =  num_attention_heads
										__magic_name__      =  attention_downsample_rate
										__magic_name__      =  num_multimask_outputs
										__magic_name__      =  iou_head_depth
										__magic_name__      =  iou_head_hidden_dim
										__magic_name__      =  layer_norm_eps





class     A_				(   snake_case_	):







				def __init__(				self				:    Union[str, Any]    ,     __lowerCamelCase				:    str=7_6_8    ,     __lowerCamelCase				:    Optional[int]=2_5_6    ,     __lowerCamelCase				:    Tuple=1_2    ,     __lowerCamelCase				:    int=1_2    ,     __lowerCamelCase				:    int=3    ,     __lowerCamelCase				:    int=1_0_2_4    ,     __lowerCamelCase				:    Any=1_6    ,     __lowerCamelCase				:    Tuple="gelu"    ,     __lowerCamelCase				:    Dict=1e-06    ,     __lowerCamelCase				:    List[Any]=0.0    ,     __lowerCamelCase				:    Optional[Any]=1e-10    ,     __lowerCamelCase				:    str=True    ,     __lowerCamelCase				:    List[str]=4.0    ,     __lowerCamelCase				:    Union[str, Any]=True    ,     __lowerCamelCase				:    str=True    ,     __lowerCamelCase				:    Optional[Any]=1_4    ,     __lowerCamelCase				:    str=[2, 5, 8, 1_1]    ,     __lowerCamelCase				:    List[Any]=1_2_8    ,     __lowerCamelCase				:    Dict=None    ,     **__lowerCamelCase				:    List[str]    ,     )					->       Optional[int]:
										super().__init__(**__lowerCamelCase						)

										__magic_name__      =  hidden_size
										__magic_name__      =  output_channels
										__magic_name__      =  num_hidden_layers
										__magic_name__      =  num_attention_heads
										__magic_name__      =  num_channels
										__magic_name__      =  image_size
										__magic_name__      =  patch_size
										__magic_name__      =  hidden_act
										__magic_name__      =  layer_norm_eps
										__magic_name__      =  attention_dropout
										__magic_name__      =  initializer_range
										__magic_name__      =  qkv_bias
										__magic_name__      =  mlp_ratio
										__magic_name__      =  use_abs_pos
										__magic_name__      =  use_rel_pos
										__magic_name__      =  window_size
										__magic_name__      =  global_attn_indexes
										__magic_name__      =  num_pos_feats
										__magic_name__      =  int(hidden_size * mlp_ratio						) if mlp_dim is None else mlp_dim





class     A_				(   snake_case_	):
				UpperCAmelCase__										=					'''sam'''
				UpperCAmelCase__										=					True







				def __init__(				self				:    Optional[Any]    ,     __lowerCamelCase				:    Dict=None    ,     __lowerCamelCase				:    Dict=None    ,     __lowerCamelCase				:    Optional[Any]=None    ,     __lowerCamelCase				:    int=0.02    ,     **__lowerCamelCase				:    List[Any]    ,     )					->       List[str]:
										super().__init__(**__lowerCamelCase						)
										__magic_name__      =  vision_config if vision_config is not None else {}
										__magic_name__      =  prompt_encoder_config if prompt_encoder_config is not None else {}
										__magic_name__      =  mask_decoder_config if mask_decoder_config is not None else {}

										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  vision_config.to_dict()
										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  prompt_encoder_config.to_dict()
										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  mask_decoder_config.to_dict()

										__magic_name__      =  SamVisionConfig(**__lowerCamelCase						)
										__magic_name__      =  SamPromptEncoderConfig(**__lowerCamelCase						)
										__magic_name__      =  SamMaskDecoderConfig(**__lowerCamelCase						)
										__magic_name__      =  initializer_range







				def      _snake_case       (				self				:    Optional[int]						)					->       str:
										__magic_name__      =  copy.deepcopy(self.__dict__						)
										__magic_name__      =  self.vision_config.to_dict()
										__magic_name__      =  self.prompt_encoder_config.to_dict()
										__magic_name__      =  self.mask_decoder_config.to_dict()
										__magic_name__      =  self.__class__.model_type
										return output



