





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


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  Dict:
    lowerCamelCase__					:   List[str]      				=	create_tensor(_lowerCamelCase				)
    lowerCamelCase__					:   Any      				=	gather(_lowerCamelCase				)
    assert gathered_tensor.tolist() == list(range(1		,			state.num_processes**2 + 1				)				)


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  Optional[Any]:
    lowerCamelCase__					:   List[str]      				=	[state.process_index]
    lowerCamelCase__					:   Optional[int]      				=	gather_object(_lowerCamelCase				)
    assert len(_lowerCamelCase				) == state.num_processes, F"""{gathered_obj}, {len(_lowerCamelCase				)} != {state.num_processes}"""
    assert gathered_obj == list(range(state.num_processes				)				), F"""{gathered_obj} != {list(range(state.num_processes				)				)}"""


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  Any:
    lowerCamelCase__					:   List[Any]      				=	create_tensor(_lowerCamelCase				)
    lowerCamelCase__					:   int      				=	broadcast(_lowerCamelCase				)
    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				)    ->  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:
        lowerCamelCase__					:   Dict      				=	torch.arange(state.num_processes + 1				).to(state.device				)
    else:
        lowerCamelCase__					:   Dict      				=	torch.arange(state.num_processes				).to(state.device				)
    lowerCamelCase__					:   int      				=	pad_across_processes(_lowerCamelCase				)
    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[Any]:
    # For now runs on only two processes
    if state.num_processes != 2:
        return
    lowerCamelCase__					:   Any      				=	create_tensor(_lowerCamelCase				)
    lowerCamelCase__					:   int      				=	reduce(_lowerCamelCase		,			'sum'				)
    lowerCamelCase__					:   str      				=	torch.tensor([4.0, 6]				).to(state.device				)
    assert torch.allclose(_lowerCamelCase		,			_lowerCamelCase				), F"""{reduced_tensor} != {truth_tensor}"""


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  List[str]:
    # For now runs on only two processes
    if state.num_processes != 2:
        return
    lowerCamelCase__					:   Any      				=	create_tensor(_lowerCamelCase				)
    lowerCamelCase__					:   Any      				=	reduce(_lowerCamelCase		,			'mean'				)
    lowerCamelCase__					:   Union[str, Any]      				=	torch.tensor([2.0, 3]				).to(state.device				)
    assert torch.allclose(_lowerCamelCase		,			_lowerCamelCase				), F"""{reduced_tensor} != {truth_tensor}"""


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  Optional[Any]:
    # For xla_spawn (TPUs)
    main()


def  SCREAMING_SNAKE_CASE   ( )    ->  Dict:
    lowerCamelCase__					:   List[Any]      				=	PartialState()
    state.print(F"""State: {state}"""				)
    state.print('testing gather'				)
    test_gather(_lowerCamelCase				)
    state.print('testing gather_object'				)
    test_gather_object(_lowerCamelCase				)
    state.print('testing broadcast'				)
    test_broadcast(_lowerCamelCase				)
    state.print('testing pad_across_processes'				)
    test_pad_across_processes(_lowerCamelCase				)
    state.print('testing reduce_sum'				)
    test_reduce_sum(_lowerCamelCase				)
    state.print('testing reduce_mean'				)
    test_reduce_mean(_lowerCamelCase				)


if __name__ == "__main__":
    main()










from ..utils import DummyObject, requires_backends

class      lowerCAmelCase							(      metaclass=__UpperCamelCase    ):
 UpperCAmelCase__									=	["""torch""", """transformers""", """onnx"""]
 def __init__(   self						:   Tuple    ,  *UpperCAmelCase						:   str    ,  **UpperCAmelCase						:   Optional[int]			)    ->			List[str]:
     requires_backends(self    ,  ['torch', 'transformers', 'onnx']			)
 @classmethod
 def   A_			(   cls						:   Union[str, Any]    ,  *UpperCAmelCase						:   Dict    ,  **UpperCAmelCase						:   List[str]			)    ->			int:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)







 @classmethod
 def   A_			(   cls						:   Any    ,  *UpperCAmelCase						:   List[Any]    ,  **UpperCAmelCase						:   Tuple			)    ->			Union[str, Any]:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)


class      lowerCAmelCase							(      metaclass=__UpperCamelCase    ):
 UpperCAmelCase__									=	["""torch""", """transformers""", """onnx"""]
 def __init__(   self						:   List[Any]    ,  *UpperCAmelCase						:   Union[str, Any]    ,  **UpperCAmelCase						:   Dict			)    ->			Any:
     requires_backends(self    ,  ['torch', 'transformers', 'onnx']			)
 @classmethod
 def   A_			(   cls						:   str    ,  *UpperCAmelCase						:   Union[str, Any]    ,  **UpperCAmelCase						:   Union[str, Any]			)    ->			Tuple:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)







 @classmethod
 def   A_			(   cls						:   List[Any]    ,  *UpperCAmelCase						:   str    ,  **UpperCAmelCase						:   Dict			)    ->			str:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)


class      lowerCAmelCase							(      metaclass=__UpperCamelCase    ):
 UpperCAmelCase__									=	["""torch""", """transformers""", """onnx"""]
 def __init__(   self						:   Dict    ,  *UpperCAmelCase						:   Dict    ,  **UpperCAmelCase						:   Dict			)    ->			Optional[int]:
     requires_backends(self    ,  ['torch', 'transformers', 'onnx']			)
 @classmethod
 def   A_			(   cls						:   Optional[Any]    ,  *UpperCAmelCase						:   Union[str, Any]    ,  **UpperCAmelCase						:   Any			)    ->			Any:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)







 @classmethod
 def   A_			(   cls						:   List[str]    ,  *UpperCAmelCase						:   Any    ,  **UpperCAmelCase						:   Dict			)    ->			Tuple:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)


class      lowerCAmelCase							(      metaclass=__UpperCamelCase    ):
 UpperCAmelCase__									=	["""torch""", """transformers""", """onnx"""]
 def __init__(   self						:   Union[str, Any]    ,  *UpperCAmelCase						:   Optional[int]    ,  **UpperCAmelCase						:   Optional[int]			)    ->			Any:
     requires_backends(self    ,  ['torch', 'transformers', 'onnx']			)
 @classmethod
 def   A_			(   cls						:   List[Any]    ,  *UpperCAmelCase						:   Dict    ,  **UpperCAmelCase						:   int			)    ->			Dict:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)







 @classmethod
 def   A_			(   cls						:   Dict    ,  *UpperCAmelCase						:   Dict    ,  **UpperCAmelCase						:   Optional[int]			)    ->			Optional[int]:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)


class      lowerCAmelCase							(      metaclass=__UpperCamelCase    ):
 UpperCAmelCase__									=	["""torch""", """transformers""", """onnx"""]
 def __init__(   self						:   List[str]    ,  *UpperCAmelCase						:   List[Any]    ,  **UpperCAmelCase						:   List[str]			)    ->			Optional[int]:
     requires_backends(self    ,  ['torch', 'transformers', 'onnx']			)
 @classmethod
 def   A_			(   cls						:   List[Any]    ,  *UpperCAmelCase						:   Optional[Any]    ,  **UpperCAmelCase						:   Optional[Any]			)    ->			str:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)







 @classmethod
 def   A_			(   cls						:   List[Any]    ,  *UpperCAmelCase						:   Optional[int]    ,  **UpperCAmelCase						:   Any			)    ->			Any:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)


class      lowerCAmelCase							(      metaclass=__UpperCamelCase    ):
 UpperCAmelCase__									=	["""torch""", """transformers""", """onnx"""]
 def __init__(   self						:   List[str]    ,  *UpperCAmelCase						:   Tuple    ,  **UpperCAmelCase						:   Optional[int]			)    ->			Optional[Any]:
     requires_backends(self    ,  ['torch', 'transformers', 'onnx']			)
 @classmethod
 def   A_			(   cls						:   Union[str, Any]    ,  *UpperCAmelCase						:   List[Any]    ,  **UpperCAmelCase						:   Optional[Any]			)    ->			Tuple:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)







 @classmethod
 def   A_			(   cls						:   Tuple    ,  *UpperCAmelCase						:   List[str]    ,  **UpperCAmelCase						:   List[str]			)    ->			Tuple:
     requires_backends(cls    ,  ['torch', 'transformers', 'onnx']			)





