



import inspect
import unittest

import requests

from transformers import MgpstrConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch
			from torch import nn

			from transformers import MgpstrForSceneTextRecognition


if is_vision_available():
			from PIL import Image

			from transformers import MgpstrProcessor
class       _lowerCAmelCase :






			"""simple docstring"""





			def __init__(					self						:							List[Any]      ,  lowercase						:							Union[str, Any]      ,  lowercase						:							Optional[Any]=False      ,  lowercase						:							Optional[Any]=13      ,  lowercase						:							List[Any]=(32, 128)      ,  lowercase						:							Optional[Any]=4      ,  lowercase						:							int=3      ,  lowercase						:							Dict=27      ,  lowercase						:							Union[str, Any]=38      ,  lowercase						:							Dict=99      ,  lowercase						:							Optional[Any]=99      ,  lowercase						:							Any=32      ,  lowercase						:							str=5      ,  lowercase						:							Union[str, Any]=4      ,  lowercase						:							Union[str, Any]=4.0      ,  lowercase						:							int=257      ,  lowercase						:							int=None      ,  )    ->       Optional[Any]:
									"""simple docstring"""







									__lowercase											=					parent
									__lowercase											=					is_training
									__lowercase											=					batch_size
									__lowercase											=					image_size
									__lowercase											=					patch_size
									__lowercase											=					num_channels
									__lowercase											=					max_token_length
									__lowercase											=					num_character_labels
									__lowercase											=					num_bpe_labels
									__lowercase											=					num_wordpiece_labels
									__lowercase											=					hidden_size
									__lowercase											=					num_hidden_layers
									__lowercase											=					num_attention_heads
									__lowercase											=					mlp_ratio
									__lowercase											=					patch_embeds_hidden_size
									__lowercase											=					output_hidden_states





			def 		snake_case__      (					self						:							Union[str, Any] )    ->       Optional[int]:
									"""simple docstring"""







									__lowercase											=					floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]] )
									__lowercase											=					self.get_config()
									return config, pixel_values





			def 		snake_case__      (					self						:							List[str] )    ->       str:
									"""simple docstring"""







									return MgpstrConfig(
									    image_size=self.image_size      ,  patch_size=self.patch_size      ,  num_channels=self.num_channels      ,  max_token_length=self.max_token_length      ,  num_character_labels=self.num_character_labels      ,  num_bpe_labels=self.num_bpe_labels      ,  num_wordpiece_labels=self.num_wordpiece_labels      ,  hidden_size=self.hidden_size      ,  num_hidden_layers=self.num_hidden_layers      ,  num_attention_heads=self.num_attention_heads      ,  mlp_ratio=self.mlp_ratio      ,  output_hidden_states=self.output_hidden_states      ,  )





			def 		snake_case__      (					self						:							Tuple      ,  lowercase						:							List[str]      ,  lowercase						:							Optional[int] )    ->       List[Any]:
									"""simple docstring"""







									__lowercase											=					MgpstrForSceneTextRecognition(lowercase )
									model.to(lowercase )
									model.eval()
									with torch.no_grad():
															__lowercase											=					model(lowercase )
									self.parent.assertEqual(
									    generated_ids[0][0].shape      ,  (self.batch_size, self.max_token_length, self.num_character_labels) )







			def 		snake_case__      (					self						:							Optional[Any] )    ->       int:
									"""simple docstring"""







									__lowercase											=					self.prepare_config_and_inputs()
									__lowercase						,      __lowercase											=					config_and_inputs
									__lowercase											=					{"""pixel_values""": pixel_values}
									return config, inputs_dict





@require_torch
class       _lowerCAmelCase (			_UpperCAmelCase     ,       _UpperCAmelCase     ,       unittest.TestCase      ):






			"""simple docstring"""





			lowercase__   :	Any  			=      (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
			lowercase__   :	List[str]  			=      {"""feature-extraction""": MgpstrForSceneTextRecognition} if is_torch_available() else {}
			lowercase__   :	List[Any]  			=      False

			lowercase__   :	List[str]  			=      False
			lowercase__   :	List[Any]  			=      False
			lowercase__   :	Union[str, Any]  			=      False
			lowercase__   :	Optional[Any]  			=      False





			def 		snake_case__      (					self						:							Any )    ->       Tuple:
									"""simple docstring"""







									__lowercase											=					MgpstrModelTester(self )
									__lowercase											=					ConfigTester(self      ,  config_class=lowercase      ,  has_text_modality=lowercase )





			def 		snake_case__      (					self						:							Dict )    ->       Optional[Any]:
									"""simple docstring"""







									self.config_tester.run_common_tests()





			def 		snake_case__      (					self						:							Dict )    ->       int:
									"""simple docstring"""







									__lowercase											=					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowercase )





			@unittest.skip(reason="""MgpstrModel does not use inputs_embeds""" )
			def 		snake_case__      (					self						:							Tuple )    ->       str:
									"""simple docstring"""







									pass





			def 		snake_case__      (					self						:							Tuple )    ->       Optional[int]:
									"""simple docstring"""







									__lowercase						,      __lowercase											=					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															__lowercase											=					model_class(lowercase )
															self.assertIsInstance(model.get_input_embeddings()      ,  (nn.Module) )
															__lowercase											=					model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(lowercase      ,  nn.Linear ) )





			def 		snake_case__      (					self						:							List[str] )    ->       Optional[int]:
									"""simple docstring"""







									__lowercase						,      __lowercase											=					self.model_tester.prepare_config_and_inputs_for_common()

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

															__lowercase											=					["""pixel_values"""]
															self.assertListEqual(arg_names[:1]      ,  lowercase )





			@unittest.skip(reason="""MgpstrModel does not support feedforward chunking""" )
			def 		snake_case__      (					self						:							str )    ->       List[str]:
									"""simple docstring"""







									pass





			def 		snake_case__      (					self						:							List[Any] )    ->       Tuple:
									"""simple docstring"""







									__lowercase						,      __lowercase											=					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															if not model_class.supports_gradient_checkpointing:
																					continue

															__lowercase											=					True
															__lowercase											=					model_class(lowercase )
															self.assertTrue(model.is_gradient_checkpointing )





			def 		snake_case__      (					self						:							Tuple )    ->       List[str]:
									"""simple docstring"""







									def check_hidden_states_output(lowercase						:							Optional[int]      ,  lowercase						:							List[str]      ,  lowercase						:							List[str] ):
															__lowercase											=					model_class(lowercase )
															model.to(lowercase )
															model.eval()

															with torch.no_grad():
																					__lowercase											=					model(**self._prepare_for_class(lowercase      ,  lowercase ) )

															__lowercase											=					outputs.hidden_states

															__lowercase											=					getattr(
															    self.model_tester      ,  """expected_num_hidden_layers"""      ,  self.model_tester.num_hidden_layers + 1 )
															self.assertEqual(len(lowercase )      ,  lowercase )

															self.assertListEqual(
															    list(hidden_states[0].shape[-2:] )      ,  [self.model_tester.patch_embeds_hidden_size, self.model_tester.hidden_size]      ,  )

									__lowercase						,      __lowercase											=					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															__lowercase											=					True
															check_hidden_states_output(lowercase      ,  lowercase      ,  lowercase )

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															__lowercase											=					True

															check_hidden_states_output(lowercase      ,  lowercase      ,  lowercase )





			def 		snake_case__      (					self						:							int )    ->       Any:
									"""simple docstring"""







									__lowercase						,      __lowercase											=					self.model_tester.prepare_config_and_inputs_for_common()

									__lowercase											=					_config_zero_init(lowercase )
									for model_class in self.all_model_classes:
															__lowercase											=					model_class(config=lowercase )
															for name, param in model.named_parameters():
																					if isinstance(lowercase      ,  (nn.Linear, nn.Convad, nn.LayerNorm) ):
																											if param.requires_grad:
																																	self.assertIn(
																																	    ((param.data.mean() * 1E9).round() / 1E9).item()      ,  [0.0, 1.0]      ,  msg=F"Parameter {name} of model {model_class} seems not properly initialized"      ,  )







			@unittest.skip(reason="""Retain_grad is tested in individual model tests""" )
			def 		snake_case__      (					self						:							Any )    ->       Optional[int]:
									"""simple docstring"""







									pass






def 			UpperCAmelCase__     (     )			->   Tuple:
						__lowercase											=					"""https://i.postimg.cc/ZKwLg2Gw/367-14.png"""
						__lowercase											=					Image.open(requests.get(lowercase__    ,							stream=lowercase__ ).raw ).convert("""RGB""" )
						return im







@require_vision
@require_torch
class       _lowerCAmelCase (			unittest.TestCase      ):






			"""simple docstring"""





			@slow
			def 		snake_case__      (					self						:							Optional[Any] )    ->       Dict:
									"""simple docstring"""







									__lowercase											=					"""alibaba-damo/mgp-str-base"""
									__lowercase											=					MgpstrForSceneTextRecognition.from_pretrained(lowercase ).to(lowercase )
									__lowercase											=					MgpstrProcessor.from_pretrained(lowercase )

									__lowercase											=					prepare_img()
									__lowercase											=					processor(images=lowercase      ,  return_tensors="""pt""" ).pixel_values.to(lowercase )

									# forward pass
									with torch.no_grad():
															__lowercase											=					model(lowercase )

									# verify the logits
									self.assertEqual(outputs.logits[0].shape      ,  torch.Size((1, 27, 38) ) )

									__lowercase											=					processor.batch_decode(outputs.logits )
									__lowercase											=					"""ticket"""

									self.assertEqual(out_strs["""generated_text"""][0]      ,  lowercase )

									__lowercase											=					torch.tensor(
									    [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]]      ,  device=lowercase      ,  )

									self.assertTrue(torch.allclose(outputs.logits[0][:, 1:4, 1:4]      ,  lowercase      ,  atol=1E-4 ) )










# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


UpperCamelCase__			=    os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
UpperCamelCase__			=    os.path.join(hf_cache_home, "accelerate")
UpperCamelCase__			=    os.path.join(cache_dir, "default_config.yaml")
UpperCamelCase__			=    os.path.join(cache_dir, "default_config.yaml")

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
			UpperCamelCase__			=    default_yaml_config_file
else:
			UpperCamelCase__			=    default_json_config_file






def 			UpperCAmelCase__     (     lowercase__ )			->   int:
						if config_file is not None:
												if not os.path.isfile(lowercase__ ):
																		raise FileNotFoundError(
																		    F"The passed configuration file `{config_file}` does not exist. "
																		    """Please pass an existing file to `accelerate launch`, or use the the default one """
																		    """created through `accelerate config` and run `accelerate launch` """
																		    """without the `--config_file` argument.""" )
						else:
												__lowercase											=					default_config_file
						with open(lowercase__    ,							"""r"""    ,							encoding="""utf-8""" ) as f:
												if config_file.endswith(""".json""" ):
																		if (
																		    json.load(lowercase__ ).get("""compute_environment"""    ,							ComputeEnvironment.LOCAL_MACHINE )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								__lowercase											=					ClusterConfig
																		else:
																								__lowercase											=					SageMakerConfig
																		return config_class.from_json_file(json_file=lowercase__ )
												else:
																		if (
																		    yaml.safe_load(lowercase__ ).get("""compute_environment"""    ,							ComputeEnvironment.LOCAL_MACHINE )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								__lowercase											=					ClusterConfig
																		else:
																								__lowercase											=					SageMakerConfig
																		return config_class.from_yaml_file(yaml_file=lowercase__ )
@dataclass
class       _lowerCAmelCase :






			"""simple docstring"""





			lowercase__   :	ComputeEnvironment
			lowercase__   :	Union[DistributedType, SageMakerDistributedType]
			lowercase__   :	str
			lowercase__   :	bool





			def 		snake_case__      (					self						:							Union[str, Any] )    ->       List[Any]:
									"""simple docstring"""







									__lowercase											=					self.__dict__
									# For serialization, it's best to convert Enums to strings (or their underlying value type).
									for key, value in result.items():
															if isinstance(lowercase      ,  lowercase ):
																					__lowercase											=					value.value
															if isinstance(lowercase      ,  lowercase ) and not bool(lowercase ):
																					__lowercase											=					None
									__lowercase											=					{k: v for k, v in result.items() if v is not None}
									return result





			@classmethod
			def 		snake_case__      (					cls						:							List[str]      ,  lowercase						:							List[str]=None )    ->       Union[str, Any]:
									"""simple docstring"""







									__lowercase											=					default_json_config_file if json_file is None else json_file
									with open(lowercase      ,  """r"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					json.load(lowercase )
									if "compute_environment" not in config_dict:
															__lowercase											=					ComputeEnvironment.LOCAL_MACHINE
									if "mixed_precision" not in config_dict:
															__lowercase											=					"""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
									if "fp16" in config_dict:  # Convert the config to the new format.
															del config_dict["fp16"]
									if "dynamo_backend" in config_dict:  # Convert the config to the new format.
															__lowercase											=					config_dict.pop("""dynamo_backend""" )
															__lowercase											=					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
									if "use_cpu" not in config_dict:
															__lowercase											=					False
									return cls(**lowercase )





			def 		snake_case__      (					self						:							Tuple      ,  lowercase						:							str )    ->       Any:
									"""simple docstring"""







									with open(lowercase      ,  """w"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					json.dumps(self.to_dict()      ,  indent=2      ,  sort_keys=lowercase ) + """\n"""
															f.write(lowercase )





			@classmethod
			def 		snake_case__      (					cls						:							List[str]      ,  lowercase						:							Optional[Any]=None )    ->       Union[str, Any]:
									"""simple docstring"""







									__lowercase											=					default_yaml_config_file if yaml_file is None else yaml_file
									with open(lowercase      ,  """r"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					yaml.safe_load(lowercase )
									if "compute_environment" not in config_dict:
															__lowercase											=					ComputeEnvironment.LOCAL_MACHINE

									if "mixed_precision" not in config_dict:
															__lowercase											=					"""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
									if isinstance(config_dict["""mixed_precision"""]      ,  lowercase ) and not config_dict["mixed_precision"]:
															__lowercase											=					"""no"""
									if "fp16" in config_dict:  # Convert the config to the new format.
															del config_dict["fp16"]
									if "dynamo_backend" in config_dict:  # Convert the config to the new format.
															__lowercase											=					config_dict.pop("""dynamo_backend""" )
															__lowercase											=					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
									if "use_cpu" not in config_dict:
															__lowercase											=					False
									return cls(**lowercase )





			def 		snake_case__      (					self						:							Union[str, Any]      ,  lowercase						:							Any )    ->       Tuple:
									"""simple docstring"""







									with open(lowercase      ,  """w"""      ,  encoding="""utf-8""" ) as f:
															yaml.safe_dump(self.to_dict()      ,  lowercase )







			def 		snake_case__      (					self						:							int )    ->       Optional[int]:
									"""simple docstring"""







									if isinstance(self.compute_environment      ,  lowercase ):
															__lowercase											=					ComputeEnvironment(self.compute_environment )
									if isinstance(self.distributed_type      ,  lowercase ):
															if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																					__lowercase											=					SageMakerDistributedType(self.distributed_type )
															else:
																					__lowercase											=					DistributedType(self.distributed_type )
									if self.dynamo_config is None:
															__lowercase											=					{}





@dataclass
class       _lowerCAmelCase (			_UpperCAmelCase      ):






			"""simple docstring"""





			lowercase__   :	int
			lowercase__   :	int  			=      0
			lowercase__   :	int  			=      1
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[int]  			=      None
			lowercase__   :	Optional[str]  			=      "static"
			lowercase__   :	Optional[bool]  			=      False
			lowercase__   :	str  			=      "main"

			# args for deepspeed_plugin
			lowercase__   :	dict  			=      None
			# args for fsdp
			lowercase__   :	dict  			=      None
			# args for megatron_lm
			lowercase__   :	dict  			=      None
			# args for ipex
			lowercase__   :	dict  			=      None
			# args for TPU
			lowercase__   :	bool  			=      False

			# args for TPU pods
			lowercase__   :	str  			=      None
			lowercase__   :	str  			=      None
			lowercase__   :	bool  			=      False
			lowercase__   :	bool  			=      False
			lowercase__   :	str  			=      None
			lowercase__   :	List[str]  			=      None
			lowercase__   :	List[str]  			=      None
			lowercase__   :	List[str]  			=      None

			# args for dynamo
			lowercase__   :	dict  			=      None





			def 		snake_case__      (					self						:							List[Any] )    ->       int:
									"""simple docstring"""







									if self.deepspeed_config is None:
															__lowercase											=					{}
									if self.fsdp_config is None:
															__lowercase											=					{}
									if self.megatron_lm_config is None:
															__lowercase											=					{}
									if self.ipex_config is None:
															__lowercase											=					{}
									return super().__post_init__()





@dataclass
class       _lowerCAmelCase (			_UpperCAmelCase      ):






			"""simple docstring"""





			lowercase__   :	str
			lowercase__   :	str
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	str  			=      "us-east-1"
			lowercase__   :	int  			=      1
			lowercase__   :	str  			=      "all"
			lowercase__   :	str  			=      F'''accelerate-sagemaker-{num_machines}'''
			lowercase__   :	str  			=      SAGEMAKER_PYTORCH_VERSION
			lowercase__   :	str  			=      SAGEMAKER_TRANSFORMERS_VERSION
			lowercase__   :	str  			=      SAGEMAKER_PYTHON_VERSION
			lowercase__   :	str  			=      None
			lowercase__   :	str  			=      None
			lowercase__   :	dict  			=      None
			lowercase__   :	dict  			=      None





