


from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
     import tensorflow as tf

     from transformers import TFBlipTextModel
     from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST







class 		_snake_case  :




 def __init__(		self					,  _lowerCamelCase					,  _lowerCamelCase=12					,  _lowerCamelCase=7					,  _lowerCamelCase=True					,  _lowerCamelCase=True					,  _lowerCamelCase=True					,  _lowerCamelCase=99					,  _lowerCamelCase=32					,  _lowerCamelCase=32					,  _lowerCamelCase=2					,  _lowerCamelCase=4					,  _lowerCamelCase=37					,  _lowerCamelCase=0.1					,  _lowerCamelCase=0.1					,  _lowerCamelCase=512					,  _lowerCamelCase=0.02					,  _lowerCamelCase=0					,  _lowerCamelCase=None					,  ):
       a						:str 							=       parent
       a						:Dict 							=       batch_size
       a						:List[Any] 							=       seq_length
       a						:int 							=       is_training
       a						:List[Any] 							=       use_input_mask
       a						:List[Any] 							=       use_labels
       a						:Optional[int] 							=       vocab_size
       a						:Any 							=       hidden_size
       a						:int 							=       projection_dim
       a						:List[Any] 							=       num_hidden_layers
       a						:Any 							=       num_attention_heads
       a						:Tuple 							=       intermediate_size
       a						:Tuple 							=       dropout
       a						:Tuple 							=       attention_dropout
       a						:Any 							=       max_position_embeddings
       a						:Optional[Any] 							=       initializer_range
       a						:List[Any] 							=       scope
       a						:Tuple 							=       bos_token_id




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:Any 							=       ids_tensor([self.batch_size, self.seq_length]					,  self.vocab_size    )

       a						:List[Any] 							=       None
       if self.use_input_mask:
             a						:int 							=       random_attention_mask([self.batch_size, self.seq_length]    )

       if input_mask is not None:
             a						:Union[str, Any] 							=       input_mask.numpy()
             a							,				a						:int 							=       input_mask.shape
             a						:str 							=       np.random.randint(1					,  seq_length - 1					,  size=(batch_size,)    )
             for batch_idx, start_index in enumerate(_lowerCamelCase    ):
                   a						:List[Any] 							=       1
                   a						:int 							=       0

       a						:Tuple 							=       self.get_config()

       return config, input_ids, tf.convert_to_tensor(_lowerCamelCase    )




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       return BlipTextConfig(
           vocab_size=self.vocab_size					,  hidden_size=self.hidden_size					,  projection_dim=self.projection_dim					,  num_hidden_layers=self.num_hidden_layers					,  num_attention_heads=self.num_attention_heads					,  intermediate_size=self.intermediate_size					,  dropout=self.dropout					,  attention_dropout=self.attention_dropout					,  max_position_embeddings=self.max_position_embeddings					,  initializer_range=self.initializer_range					,  bos_token_id=self.bos_token_id					,  )




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase					,  _lowerCamelCase					,  _lowerCamelCase    ):
       a						:Optional[int] 							=       TFBlipTextModel(config=_lowerCamelCase    )
       a						:str 							=       model(_lowerCamelCase					,  attention_mask=_lowerCamelCase					,  training=_lowerCamelCase    )
       a						:Optional[int] 							=       model(_lowerCamelCase					,  training=_lowerCamelCase    )
       self.parent.assertEqual(result.last_hidden_state.shape					,  (self.batch_size, self.seq_length, self.hidden_size)    )
       self.parent.assertEqual(result.pooler_output.shape					,  (self.batch_size, self.hidden_size)    )




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:str 							=       self.prepare_config_and_inputs()
       a							,				a							,				a						:Tuple 							=       config_and_inputs
       a						:Dict 							=       {'''input_ids''': input_ids, '''attention_mask''': input_mask}
       return config, inputs_dict







@require_tf
class 		_snake_case  (      _snake_case						,    unittest.TestCase							):
 SCREAMING_SNAKE_CASE__      =       (TFBlipTextModel,) if is_tf_available() else ()
 SCREAMING_SNAKE_CASE__      =       False
 SCREAMING_SNAKE_CASE__      =       False
 SCREAMING_SNAKE_CASE__      =       False




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:Tuple 							=       BlipTextModelTester(self    )
       a						:List[str] 							=       ConfigTester(self					,  config_class=_lowerCamelCase					,  hidden_size=37    )




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




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:Any 							=       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_lowerCamelCase    )




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       pass




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       pass




 @unittest.skip(reason='''Blip does not use inputs_embeds'''    )
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       pass




 @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING'''    )
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       pass




 @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING'''    )
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       pass




 @slow
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             a						:Any 							=       TFBlipTextModel.from_pretrained(_lowerCamelCase    )
             self.assertIsNotNone(_lowerCamelCase    )




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase=True    ):
       super().test_pt_tf_model_equivalence(allow_missing_keys=_lowerCamelCase    )









# 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.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


snake_case				:    int       				=     '''Create a default config file for Accelerate with only a few flags set.'''
def 				__lowerCamelCase						( UpperCAmelCase_						:		Optional[Any]="no" ,  UpperCAmelCase_						:		str = default_json_config_file ,  UpperCAmelCase_						:		bool = False						):




      """simple docstring"""





      a						:List[str] 							=       Path(UpperCAmelCase_						)
      path.parent.mkdir(parents=UpperCAmelCase_ ,  exist_ok=UpperCAmelCase_						)
      if path.exists():
            print(
                F'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'''						)
            return False
      a						:Optional[Any] 							=       mixed_precision.lower()
      if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
            raise ValueError(
                F'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'''						)
      a						:List[Any] 							=       {
          '''compute_environment''': '''LOCAL_MACHINE''',
          '''mixed_precision''': mixed_precision,
      }
      if torch.cuda.is_available():
            a						:Dict 							=       torch.cuda.device_count()
            a						:Tuple 							=       num_gpus
            a						:int 							=       False
            if num_gpus > 1:
                  a						:str 							=       '''MULTI_GPU'''
            else:
                  a						:List[Any] 							=       '''NO'''
      elif is_xpu_available() and use_xpu:
            a						:List[Any] 							=       torch.xpu.device_count()
            a						:Optional[int] 							=       num_xpus
            a						:List[Any] 							=       False
            if num_xpus > 1:
                  a						:int 							=       '''MULTI_XPU'''
            else:
                  a						:str 							=       '''NO'''
      elif is_npu_available():
            a						:List[str] 							=       torch.npu.device_count()
            a						:Any 							=       num_npus
            a						:Optional[int] 							=       False
            if num_npus > 1:
                  a						:List[str] 							=       '''MULTI_NPU'''
            else:
                  a						:Dict 							=       '''NO'''
      else:
            a						:str 							=       0
            a						:Optional[Any] 							=       True
            a						:Optional[Any] 							=       1
            a						:str 							=       '''NO'''
      a						:List[str] 							=       ClusterConfig(**UpperCAmelCase_						)
      config.to_json_file(UpperCAmelCase_						)
      return path
def 				__lowerCamelCase						( UpperCAmelCase_						:		List[str] ,  UpperCAmelCase_						:		Union[str, Any]						):




      """simple docstring"""





      a						:List[Any] 							=       parser.add_parser('''default''' ,  parents=UpperCAmelCase_ ,  help=UpperCAmelCase_ ,  formatter_class=UpperCAmelCase_						)
      parser.add_argument(
          '''--config_file''' ,  default=UpperCAmelCase_ ,  help=(
              '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
              '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
              '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
              '''with \'huggingface\'.'''
          ) ,  dest='''save_location''' ,  )

      parser.add_argument(
          '''--mixed_precision''' ,  choices=['''no''', '''fp16''', '''bf16'''] ,  type=UpperCAmelCase_ ,  help='''Whether or not to use mixed precision training. '''
          '''Choose between FP16 and BF16 (bfloat16) training. '''
          '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.''' ,  default='''no''' ,  )
      parser.set_defaults(func=UpperCAmelCase_						)
      return parser






def 				__lowerCamelCase						( UpperCAmelCase_						:		int						):




      """simple docstring"""





      a						:Optional[Any] 							=       write_basic_config(args.mixed_precision ,  args.save_location						)
      if config_file:
            print(F'''accelerate configuration saved at {config_file}'''						)





