





# 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 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				List[Any]     ):
		return (torch.arange(state.num_processes     ) + 1.0 + (state.num_processes * state.process_index)).to(state.device     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Dict     ):
		SCREAMING_SNAKE_CASE__								=   create_tensor(UpperCamelCase__     )
		SCREAMING_SNAKE_CASE__								=   gather(UpperCamelCase__     )
		assert gathered_tensor.tolist() == list(range(1       , state.num_processes**2 + 1     )     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Tuple     ):
		SCREAMING_SNAKE_CASE__								=   [state.process_index]
		SCREAMING_SNAKE_CASE__								=   gather_object(UpperCamelCase__     )
		assert len(UpperCamelCase__     ) == state.num_processes, f'''{gathered_obj}, {len(UpperCamelCase__     )} != {state.num_processes}'''
		assert gathered_obj == list(range(state.num_processes     )     ), f'''{gathered_obj} != {list(range(state.num_processes     )     )}'''






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				str     ):
		SCREAMING_SNAKE_CASE__								=   create_tensor(UpperCamelCase__     )
		SCREAMING_SNAKE_CASE__								=   broadcast(UpperCamelCase__     )
		assert broadcasted_tensor.shape == torch.Size([state.num_processes]     )
		assert broadcasted_tensor.tolist() == list(range(1       , state.num_processes + 1     )     )






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				List[str]     ):
		# We need to pad the tensor with one more element if we are the main process
		# to ensure that we can pad
		if state.is_main_process:
				SCREAMING_SNAKE_CASE__								=   torch.arange(state.num_processes + 1     ).to(state.device     )
		else:
				SCREAMING_SNAKE_CASE__								=   torch.arange(state.num_processes     ).to(state.device     )
		SCREAMING_SNAKE_CASE__								=   pad_across_processes(UpperCamelCase__     )
		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 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Optional[int]     ):
		# For now runs on only two processes
		if state.num_processes != 2:
				return
		SCREAMING_SNAKE_CASE__								=   create_tensor(UpperCamelCase__     )
		SCREAMING_SNAKE_CASE__								=   reduce(UpperCamelCase__       , """sum"""     )
		SCREAMING_SNAKE_CASE__								=   torch.tensor([4.0, 6]     ).to(state.device     )
		assert torch.allclose(UpperCamelCase__       , UpperCamelCase__     ), f'''{reduced_tensor} != {truth_tensor}'''






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				str     ):
		# For now runs on only two processes
		if state.num_processes != 2:
				return
		SCREAMING_SNAKE_CASE__								=   create_tensor(UpperCamelCase__     )
		SCREAMING_SNAKE_CASE__								=   reduce(UpperCamelCase__       , """mean"""     )
		SCREAMING_SNAKE_CASE__								=   torch.tensor([2.0, 3]     ).to(state.device     )
		assert torch.allclose(UpperCamelCase__       , UpperCamelCase__     ), f'''{reduced_tensor} != {truth_tensor}'''






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				Optional[int]     ):
		# For xla_spawn (TPUs)
		main()






def 					SCREAMING_SNAKE_CASE__				(							):
		SCREAMING_SNAKE_CASE__								=   PartialState()
		state.print(f'''State: {state}'''     )
		state.print("""testing gather"""     )
		test_gather(UpperCamelCase__     )
		state.print("""testing gather_object"""     )
		test_gather_object(UpperCamelCase__     )
		state.print("""testing broadcast"""     )
		test_broadcast(UpperCamelCase__     )
		state.print("""testing pad_across_processes"""     )
		test_pad_across_processes(UpperCamelCase__     )
		state.print("""testing reduce_sum"""     )
		test_reduce_sum(UpperCamelCase__     )
		state.print("""testing reduce_mean"""     )
		test_reduce_mean(UpperCamelCase__     )


if __name__ == "__main__":
	main()






import copy

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


_lowerCamelCase 					=      logging.get_logger(__name__)




class 	UpperCamelCase_							(  UpperCamelCase__     ):
							lowerCamelCase_							     =       "encoder-decoder"
							lowerCamelCase_							     =       True


							def __init__(				self     :Optional[int]				,					**__A     :str		) -> int:



									"""simple docstring"""



									super().__init__(**__A		)
									assert (
									    "encoder" in kwargs and "decoder" in kwargs
									), "Config has to be initialized with encoder and decoder config"
									SCREAMING_SNAKE_CASE__								=   kwargs.pop("""encoder"""		)
									SCREAMING_SNAKE_CASE__								=   encoder_config.pop("""model_type"""		)
									SCREAMING_SNAKE_CASE__								=   kwargs.pop("""decoder"""		)
									SCREAMING_SNAKE_CASE__								=   decoder_config.pop("""model_type"""		)

									from ..auto.configuration_auto import AutoConfig

									SCREAMING_SNAKE_CASE__								=   AutoConfig.for_model(__A				,					**__A		)
									SCREAMING_SNAKE_CASE__								=   AutoConfig.for_model(__A				,					**__A		)
									SCREAMING_SNAKE_CASE__								=   True


							@classmethod
							def   _snake_case	(				cls     :str				,					__A     :PretrainedConfig				,					__A     :PretrainedConfig				,					**__A     :List[str]		) -> PretrainedConfig:



									"""simple docstring"""



									logger.info("""Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config"""		)
									SCREAMING_SNAKE_CASE__								=   True
									SCREAMING_SNAKE_CASE__								=   True

									return cls(encoder=encoder_config.to_dict()				,					decoder=decoder_config.to_dict()				,					**__A		)


							def   _snake_case	(				self     :str		) -> Union[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   copy.deepcopy(self.__dict__		)
									SCREAMING_SNAKE_CASE__								=   self.encoder.to_dict()
									SCREAMING_SNAKE_CASE__								=   self.decoder.to_dict()
									SCREAMING_SNAKE_CASE__								=   self.__class__.model_type
									return output