'''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  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]       ):



     """simple docstring"""





     return (torch.arange(state.num_processes       ) + 1.0 + (state.num_processes * state.process_index)).to(state.device       )


def  _lowerCamelCase   (				lowerCamelCase_ :							List[str]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Dict       =				create_tensor(lowerCamelCase_       )
     UpperCAmelCase_							:       Any       =				gather(lowerCamelCase_       )
     assert gathered_tensor.tolist() == list(range(1     ,					state.num_processes**2 + 1       )       )


def  _lowerCamelCase   (				lowerCamelCase_ :							int       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[str]       =				[state.process_index]
     UpperCAmelCase_							:       str       =				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  _lowerCamelCase   (				lowerCamelCase_ :							int       ):



     """simple docstring"""





     UpperCAmelCase_							:       Union[str, Any]       =				create_tensor(lowerCamelCase_       )
     UpperCAmelCase_							:       List[Any]       =				broadcast(lowerCamelCase_       )
     assert broadcasted_tensor.shape == torch.Size([state.num_processes]       )
     assert broadcasted_tensor.tolist() == list(range(1     ,					state.num_processes + 1       )       )


def  _lowerCamelCase   (				lowerCamelCase_ :							str       ):



     """simple docstring"""





     if state.is_main_process:
          UpperCAmelCase_							:       List[Any]       =				torch.arange(state.num_processes + 1       ).to(state.device       )
     else:
          UpperCAmelCase_							:       Union[str, Any]       =				torch.arange(state.num_processes       ).to(state.device       )
     UpperCAmelCase_							:       List[Any]       =				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  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]       ):



     """simple docstring"""





     if state.num_processes != 2:
          return
     UpperCAmelCase_							:       Tuple       =				create_tensor(lowerCamelCase_       )
     UpperCAmelCase_							:       List[str]       =				reduce(lowerCamelCase_     ,					'sum'       )
     UpperCAmelCase_							:       List[Any]       =				torch.tensor([4.0, 6]       ).to(state.device       )
     assert torch.allclose(lowerCamelCase_     ,					lowerCamelCase_       ), F'''{reduced_tensor} != {truth_tensor}'''


def  _lowerCamelCase   (				lowerCamelCase_ :							List[str]       ):



     """simple docstring"""





     if state.num_processes != 2:
          return
     UpperCAmelCase_							:       Optional[Any]       =				create_tensor(lowerCamelCase_       )
     UpperCAmelCase_							:       Union[str, Any]       =				reduce(lowerCamelCase_     ,					'mean'       )
     UpperCAmelCase_							:       List[Any]       =				torch.tensor([2.0, 3]       ).to(state.device       )
     assert torch.allclose(lowerCamelCase_     ,					lowerCamelCase_       ), F'''{reduced_tensor} != {truth_tensor}'''


def  _lowerCamelCase   (				lowerCamelCase_ :							Any       ):



     """simple docstring"""





     main()


def  _lowerCamelCase   (				):



     """simple docstring"""





     UpperCAmelCase_							:       Union[str, 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()







'''simple docstring'''


import unittest

from transformers.utils.backbone_utils import (
    BackboneMixin,
    get_aligned_output_features_output_indices,
    verify_out_features_out_indices,
)






class 					__SCREAMING_SNAKE_CASE						(	unittest.TestCase	):







  '''simple docstring'''






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       int       =				['a', 'b', 'c']

       # Defaults to last layer if both are None
       UpperCAmelCase_       ,      UpperCAmelCase_							:       List[str]       =				get_aligned_output_features_output_indices(snake_case_				,		snake_case_				,		snake_case_						)
       self.assertEqual(snake_case_				,		['c']						)
       self.assertEqual(snake_case_				,		[2]						)

       # Out indices set to match out features
       UpperCAmelCase_       ,      UpperCAmelCase_							:       int       =				get_aligned_output_features_output_indices(['a', 'c']				,		snake_case_				,		snake_case_						)
       self.assertEqual(snake_case_				,		['a', 'c']						)
       self.assertEqual(snake_case_				,		[0, 2]						)

       # Out features set to match out indices
       UpperCAmelCase_       ,      UpperCAmelCase_							:       List[Any]       =				get_aligned_output_features_output_indices(snake_case_				,		[0, 2]				,		snake_case_						)
       self.assertEqual(snake_case_				,		['a', 'c']						)
       self.assertEqual(snake_case_				,		[0, 2]						)

       # Out features selected from negative indices
       UpperCAmelCase_       ,      UpperCAmelCase_							:       int       =				get_aligned_output_features_output_indices(snake_case_				,		[-3, -1]				,		snake_case_						)
       self.assertEqual(snake_case_				,		['a', 'c']						)
       self.assertEqual(snake_case_				,		[-3, -1]						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       with self.assertRaises(snake_case_						):
            verify_out_features_out_indices(['a', 'b']				,		(0, 1)				,		snake_case_						)

       # Out features must be a list
       with self.assertRaises(snake_case_						):
            verify_out_features_out_indices(('a', 'b')				,		(0, 1)				,		['a', 'b']						)

       # Out features must be a subset of stage names
       with self.assertRaises(snake_case_						):
            verify_out_features_out_indices(['a', 'b']				,		(0, 1)				,		['a']						)

       # Out indices must be a list or tuple
       with self.assertRaises(snake_case_						):
            verify_out_features_out_indices(snake_case_				,		0				,		['a', 'b']						)

       # Out indices must be a subset of stage names
       with self.assertRaises(snake_case_						):
            verify_out_features_out_indices(snake_case_				,		(0, 1)				,		['a']						)

       # Out features and out indices must be the same length
       with self.assertRaises(snake_case_						):
            verify_out_features_out_indices(['a', 'b']				,		(0,)				,		['a', 'b', 'c']						)

       # Out features should match out indices
       with self.assertRaises(snake_case_						):
            verify_out_features_out_indices(['a', 'b']				,		(0, 2)				,		['a', 'b', 'c']						)

       # Out features and out indices should be in order
       with self.assertRaises(snake_case_						):
            verify_out_features_out_indices(['b', 'a']				,		(0, 1)				,		['a', 'b']						)

       # Check passes with valid inputs
       verify_out_features_out_indices(['a', 'b', 'd']				,		(0, 1, -1)				,		['a', 'b', 'c', 'd']						)






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       List[str]       =				BackboneMixin()

       UpperCAmelCase_							:       Any       =				['a', 'b', 'c']
       UpperCAmelCase_							:       str       =				['a', 'c']
       UpperCAmelCase_							:       str       =				[0, 2]

       # Check that the output features and indices are set correctly
       self.assertEqual(backbone.out_features				,		['a', 'c']						)
       self.assertEqual(backbone.out_indices				,		[0, 2]						)

       # Check out features and indices are updated correctly
       UpperCAmelCase_							:       str       =				['a', 'b']
       self.assertEqual(backbone.out_features				,		['a', 'b']						)
       self.assertEqual(backbone.out_indices				,		[0, 1]						)

       UpperCAmelCase_							:       Optional[int]       =				[-3, -1]
       self.assertEqual(backbone.out_features				,		['a', 'c']						)
       self.assertEqual(backbone.out_indices				,		[-3, -1]						)






