


'''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__					(	UpperCAmelCase_    :				Dict							)     ->		Any:
     return (torch.arange(state.num_processes							) + 1.0 + (state.num_processes * state.process_index)).to(state.device							)



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				str							)     ->		Optional[Any]:
     __lowerCamelCase   :	Optional[int]								=		create_tensor(UpperCAmelCase_							)
     __lowerCamelCase   :	int								=		gather(UpperCAmelCase_							)
     assert gathered_tensor.tolist() == list(range(1      ,    state.num_processes**2 + 1							)							)



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				Optional[int]							)     ->		Any:
     __lowerCamelCase   :	str								=		[state.process_index]
     __lowerCamelCase   :	List[str]								=		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 			UpperCAmelCase__					(	UpperCAmelCase_    :				Tuple							)     ->		List[Any]:
     __lowerCamelCase   :	Union[str, Any]								=		create_tensor(UpperCAmelCase_							)
     __lowerCamelCase   :	Union[str, Any]								=		broadcast(UpperCAmelCase_							)
     assert broadcasted_tensor.shape == torch.Size([state.num_processes]							)
     assert broadcasted_tensor.tolist() == list(range(1      ,    state.num_processes + 1							)							)



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				int							)     ->		Dict:
     # 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   :	Union[str, Any]								=		torch.arange(state.num_processes							).to(state.device							)
     __lowerCamelCase   :	int								=		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 			UpperCAmelCase__					(	UpperCAmelCase_    :				str							)     ->		int:
     # For now runs on only two processes
     if state.num_processes != 2:
          return
     __lowerCamelCase   :	Dict								=		create_tensor(UpperCAmelCase_							)
     __lowerCamelCase   :	Tuple								=		reduce(UpperCAmelCase_      ,    'sum'							)
     __lowerCamelCase   :	Union[str, Any]								=		torch.tensor([4.0, 6]							).to(state.device							)
     assert torch.allclose(UpperCAmelCase_      ,    UpperCAmelCase_							), F'{reduced_tensor} != {truth_tensor}'



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				List[str]							)     ->		Optional[int]:
     # For now runs on only two processes
     if state.num_processes != 2:
          return
     __lowerCamelCase   :	Dict								=		create_tensor(UpperCAmelCase_							)
     __lowerCamelCase   :	Optional[Any]								=		reduce(UpperCAmelCase_      ,    'mean'							)
     __lowerCamelCase   :	List[Any]								=		torch.tensor([2.0, 3]							).to(state.device							)
     assert torch.allclose(UpperCAmelCase_      ,    UpperCAmelCase_							), F'{reduced_tensor} != {truth_tensor}'



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				int							)     ->		Tuple:
     # For xla_spawn (TPUs)
     main()



def 			UpperCAmelCase__					(	)     ->		List[Any]:
     __lowerCamelCase   :	Dict								=		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()










'''simple docstring'''



A__		:					Optional[int]												=  """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"""



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				bytes							)     ->		bytes:
     # Make sure the supplied data is a bytes-like object
     if not isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							):
          __lowerCamelCase   :	Dict								=		F'a bytes-like object is required, not \'{data.__class__.__name__}\''
          raise TypeError(UpperCAmelCase_							)

     __lowerCamelCase   :	Optional[int]								=		''.join(bin(UpperCAmelCase_							)[2:].zfill(8							) for byte in data							)

     __lowerCamelCase   :	Any								=		len(UpperCAmelCase_							) % 6 != 0

     if padding_needed:
          # The padding that will be added later
          __lowerCamelCase   :	int								=		B'=' * ((6 - len(UpperCAmelCase_							) % 6) // 2)

          # Append binary_stream with arbitrary binary digits (0's by default) to make its
          # length a multiple of 6.
          binary_stream += "0" * (6 - len(UpperCAmelCase_							) % 6)
     else:
          __lowerCamelCase   :	str								=		B''

     # Encode every 6 binary digits to their corresponding Base64 character
     return (
         "".join(
             B64_CHARSET[int(binary_stream[index : index + 6]      ,    2							)]
             for index in range(0      ,    len(UpperCAmelCase_							)      ,    6							)							).encode()
         + padding
     )



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				str							)     ->		bytes:
     # Make sure encoded_data is either a string or a bytes-like object
     if not isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							) and not isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							):
          __lowerCamelCase   :	Dict								=		(
              'argument should be a bytes-like object or ASCII string, '
              F'not \'{encoded_data.__class__.__name__}\''
          )
          raise TypeError(UpperCAmelCase_							)

     # In case encoded_data is a bytes-like object, make sure it contains only
     # ASCII characters so we convert it to a string object
     if isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							):
          try:
               __lowerCamelCase   :	int								=		encoded_data.decode('utf-8'							)
          except UnicodeDecodeError:
               raise ValueError('base64 encoded data should only contain ASCII characters'							)

     __lowerCamelCase   :	Union[str, Any]								=		encoded_data.count('='							)

     # Check if the encoded string contains non base64 characters
     if padding:
          assert all(
              char in B64_CHARSET for char in encoded_data[:-padding]							), "Invalid base64 character(s) found."
     else:
          assert all(
              char in B64_CHARSET for char in encoded_data							), "Invalid base64 character(s) found."

     # Check the padding
     assert len(UpperCAmelCase_							) % 4 == 0 and padding < 3, "Incorrect padding"

     if padding:
          # Remove padding if there is one
          __lowerCamelCase   :	Any								=		encoded_data[:-padding]

          __lowerCamelCase   :	Optional[Any]								=		''.join(
              bin(B64_CHARSET.index(UpperCAmelCase_							)							)[2:].zfill(6							) for char in encoded_data							)[: -padding * 2]
     else:
          __lowerCamelCase   :	Any								=		''.join(
              bin(B64_CHARSET.index(UpperCAmelCase_							)							)[2:].zfill(6							) for char in encoded_data							)

     __lowerCamelCase   :	str								=		[
         int(binary_stream[index : index + 8]      ,    2							)
         for index in range(0      ,    len(UpperCAmelCase_							)      ,    8							)
     ]

     return bytes(UpperCAmelCase_							)


if __name__ == "__main__":
      import doctest

      doctest.testmod()






