
'''simple docstring'''

# Copyright 2023 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 torch

from accelerate import PartialState
from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce


def 		_UpperCAmelCase (     _lowerCamelCase  :				Tuple						)			->  Any:
  return (torch.arange(state.num_processes						) + 1.0 + (state.num_processes * state.process_index)).to(state.device						)


def 		_UpperCAmelCase (     _lowerCamelCase  :				Union[str, Any]						)			->  Any:
  _lowerCAmelCase				:     int       =    create_tensor(_snake_case						)
  _lowerCAmelCase				:     Any       =    gather(_snake_case						)
  assert gathered_tensor.tolist() == list(range(1     ,					state.num_processes**2 + 1						)						)


def 		_UpperCAmelCase (     _lowerCamelCase  :				List[str]						)			->  Dict:
  _lowerCAmelCase				:     Optional[Any]       =    [state.process_index]
  _lowerCAmelCase				:     str       =    gather_object(_snake_case						)
  assert len(_snake_case						) == state.num_processes, f'{gathered_obj}, {len(_snake_case						)} != {state.num_processes}'
  assert gathered_obj == list(range(state.num_processes						)						), f'{gathered_obj} != {list(range(state.num_processes						)						)}'


def 		_UpperCAmelCase (     _lowerCamelCase  :				Union[str, Any]						)			->  Any:
  _lowerCAmelCase				:     Any       =    create_tensor(_snake_case						)
  _lowerCAmelCase				:     List[Any]       =    broadcast(_snake_case						)
  assert broadcasted_tensor.shape == torch.Size([state.num_processes]						)
  assert broadcasted_tensor.tolist() == list(range(1     ,					state.num_processes + 1						)						)


def 		_UpperCAmelCase (     _lowerCamelCase  :				Optional[int]						)			->  int:






  if state.is_main_process:
    _lowerCAmelCase				:     Optional[int]       =    torch.arange(state.num_processes + 1						).to(state.device						)
  else:
    _lowerCAmelCase				:     Optional[int]       =    torch.arange(state.num_processes						).to(state.device						)
  _lowerCAmelCase				:     Dict       =    pad_across_processes(_snake_case						)
  assert padded_tensor.shape == torch.Size([state.num_processes + 1]						)
  if not state.is_main_process:
    assert padded_tensor.tolist() == list(range(0     ,					state.num_processes						)						) + [0]


def 		_UpperCAmelCase (     _lowerCamelCase  :				int						)			->  List[str]:






  if state.num_processes != 2:
    return
  _lowerCAmelCase				:     Dict       =    create_tensor(_snake_case						)
  _lowerCAmelCase				:     Optional[int]       =    reduce(_snake_case     ,					"""sum"""						)
  _lowerCAmelCase				:     Optional[Any]       =    torch.tensor([4.0, 6]						).to(state.device						)
  assert torch.allclose(_snake_case     ,					_snake_case						), f'{reduced_tensor} != {truth_tensor}'


def 		_UpperCAmelCase (     _lowerCamelCase  :				Dict						)			->  List[str]:






  if state.num_processes != 2:
    return
  _lowerCAmelCase				:     Tuple       =    create_tensor(_snake_case						)
  _lowerCAmelCase				:     Tuple       =    reduce(_snake_case     ,					"""mean"""						)
  _lowerCAmelCase				:     Optional[int]       =    torch.tensor([2.0, 3]						).to(state.device						)
  assert torch.allclose(_snake_case     ,					_snake_case						), f'{reduced_tensor} != {truth_tensor}'


def 		_UpperCAmelCase (     _lowerCamelCase  :				str						)			->  Optional[Any]:
  main()


def 		_UpperCAmelCase (     )			->  str:
  _lowerCAmelCase				:     Any       =    PartialState()
  state.print(f'State: {state}'						)
  state.print("""testing gather"""						)
  test_gather(_snake_case						)
  state.print("""testing gather_object"""						)
  test_gather_object(_snake_case						)
  state.print("""testing broadcast"""						)
  test_broadcast(_snake_case						)
  state.print("""testing pad_across_processes"""						)
  test_pad_across_processes(_snake_case						)
  state.print("""testing reduce_sum"""						)
  test_reduce_sum(_snake_case						)
  state.print("""testing reduce_mean"""						)
  test_reduce_mean(_snake_case						)


if __name__ == "__main__":
     main()





import copy
import os
from typing import Union

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


_lowerCAmelCase					:			Optional[int]  				=			logging.get_logger(__name__)

_lowerCAmelCase					:			List[str]  				=			{
    "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json",
}






class 	__magic_name__    (			lowerCAmelCase_      ):
			SCREAMING_SNAKE_CASE							   =						'git_vision_model'





			def __init__(		self					,  __snake_case=768					,  __snake_case=3072					,  __snake_case=12					,  __snake_case=12					,  __snake_case=3					,  __snake_case=224					,  __snake_case=16					,  __snake_case="quick_gelu"					,  __snake_case=1e-5					,  __snake_case=0.0					,  __snake_case=0.02					,  **__snake_case					,  )   -> int:




						'''simple docstring'''
						super().__init__(**__snake_case					)

						__a        =hidden_size
						__a        =intermediate_size
						__a        =num_hidden_layers
						__a        =num_attention_heads
						__a        =num_channels
						__a        =patch_size
						__a        =image_size
						__a        =initializer_range
						__a        =attention_dropout
						__a        =layer_norm_eps
						__a        =hidden_act





			@classmethod
			def 		__magic_name__    (		cls					,  __snake_case					,  **__snake_case					)   -> "PretrainedConfig":




						'''simple docstring'''
						cls._set_token_in_kwargs(__snake_case					)

						__a      ,    __a        =cls.get_config_dict(__snake_case					,  **__snake_case					)

						# get the vision config dict if we are loading from GITConfig
						if config_dict.get('model_type'					) == "git":
									__a        =config_dict['vision_config']

						if "model_type" in config_dict and hasattr(cls					,  'model_type'					) and config_dict["model_type"] != cls.model_type:
									logger.warning(
									    f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
									    f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'					)

						return cls.from_dict(__snake_case					,  **__snake_case					)






class 	__magic_name__    (			lowerCAmelCase_      ):
			SCREAMING_SNAKE_CASE							   =						'git'





			def __init__(		self					,  __snake_case=None					,  __snake_case=3_0522					,  __snake_case=768					,  __snake_case=6					,  __snake_case=12					,  __snake_case=3072					,  __snake_case="gelu"					,  __snake_case=0.1					,  __snake_case=0.1					,  __snake_case=1024					,  __snake_case=0.02					,  __snake_case=1e-12					,  __snake_case=0					,  __snake_case="absolute"					,  __snake_case=True					,  __snake_case=False					,  __snake_case=101					,  __snake_case=102					,  __snake_case=None					,  **__snake_case					,  )   -> Optional[int]:




						'''simple docstring'''
						super().__init__(bos_token_id=__snake_case					,  eos_token_id=__snake_case					,  pad_token_id=__snake_case					,  **__snake_case					)

						if vision_config is None:
									__a        ={}
									logger.info('vision_config is None. initializing the GitVisionConfig with default values.'					)

						__a        =GitVisionConfig(**__snake_case					)
						__a        =vocab_size
						__a        =hidden_size
						__a        =num_hidden_layers
						__a        =num_attention_heads
						__a        =hidden_act
						__a        =intermediate_size
						__a        =hidden_dropout_prob
						__a        =attention_probs_dropout_prob
						__a        =max_position_embeddings
						__a        =initializer_range
						__a        =layer_norm_eps
						__a        =position_embedding_type
						__a        =use_cache
						__a        =tie_word_embeddings
						__a        =num_image_with_embedding

						__a        =bos_token_id
						__a        =eos_token_id





			def 		__magic_name__    (		self					)   -> Optional[Any]:




						'''simple docstring'''
						__a        =copy.deepcopy(self.__dict__					)
						__a        =self.vision_config.to_dict()
						__a        =self.__class__.model_type
						return output






