





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

def   a_   (			lowerCAmelCase_				:      List[str]     ):
   __lowerCAmelCase							     =     create_tensor(lowercase__     )
   __lowerCAmelCase							     =     gather(lowercase__     )
   assert gathered_tensor.tolist() == list(range(1,     state.num_processes**2 + 1     )     )

def   a_   (			lowerCAmelCase_				:      Optional[int]     ):
   __lowerCAmelCase							     =     [state.process_index]
   __lowerCAmelCase							     =     gather_object(lowercase__     )
   assert len(lowercase__     ) == state.num_processes, F"""{gathered_obj}, {len(lowercase__     )} != {state.num_processes}"""
   assert gathered_obj == list(range(state.num_processes     )     ), F"""{gathered_obj} != {list(range(state.num_processes     )     )}"""

def   a_   (			lowerCAmelCase_				:      int     ):
   __lowerCAmelCase							     =     create_tensor(lowercase__     )
   __lowerCAmelCase							     =     broadcast(lowercase__     )
   assert broadcasted_tensor.shape == torch.Size([state.num_processes]     )
   assert broadcasted_tensor.tolist() == list(range(1,     state.num_processes + 1     )     )

def   a_   (			lowerCAmelCase_				:      Tuple     ):





   if state.is_main_process:
      __lowerCAmelCase							     =     torch.arange(state.num_processes + 1     ).to(state.device     )
   else:
      __lowerCAmelCase							     =     torch.arange(state.num_processes     ).to(state.device     )
   __lowerCAmelCase							     =     pad_across_processes(lowercase__     )
   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   a_   (			lowerCAmelCase_				:      Tuple     ):





   if state.num_processes != 2:
      return
   __lowerCAmelCase							     =     create_tensor(lowercase__     )
   __lowerCAmelCase							     =     reduce(lowercase__,     'sum'     )
   __lowerCAmelCase							     =     torch.tensor([4.0, 6]     ).to(state.device     )
   assert torch.allclose(lowercase__,     lowercase__     ), F"""{reduced_tensor} != {truth_tensor}"""

def   a_   (			lowerCAmelCase_				:      int     ):





   if state.num_processes != 2:
      return
   __lowerCAmelCase							     =     create_tensor(lowercase__     )
   __lowerCAmelCase							     =     reduce(lowercase__,     'mean'     )
   __lowerCAmelCase							     =     torch.tensor([2.0, 3]     ).to(state.device     )
   assert torch.allclose(lowercase__,     lowercase__     ), F"""{reduced_tensor} != {truth_tensor}"""

def   a_   (			lowerCAmelCase_				:      Dict     ):
   main()

def   a_   (			):
   __lowerCAmelCase							     =     PartialState()
   state.print(F"""State: {state}"""     )
   state.print('testing gather'     )
   test_gather(lowercase__     )
   state.print('testing gather_object'     )
   test_gather_object(lowercase__     )
   state.print('testing broadcast'     )
   test_broadcast(lowercase__     )
   state.print('testing pad_across_processes'     )
   test_pad_across_processes(lowercase__     )
   state.print('testing reduce_sum'     )
   test_reduce_sum(lowercase__     )
   state.print('testing reduce_mean'     )
   test_reduce_mean(lowercase__     )


if __name__ == "__main__":
     main()








import unittest

import numpy as np
import torch

from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad



class     _UpperCAmelCase   (   unittest.TestCase   ):

  """simple docstring"""


  def     lowercase		(    self			:		Any					)							->						Optional[int]:
     __lowerCAmelCase							     =     1_0






  def     lowercase		(    self			:		int					)							->						Union[str, Any]:
     __lowerCAmelCase							     =     [1, 2, 3, 4]
     __lowerCAmelCase							     =     [1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
     self.assertEqual(truncate_or_pad(lowerCAmelCase_ ,  self.block_size ,  0					) ,  lowerCAmelCase_					)






  def     lowercase		(    self			:		Optional[Any]					)							->						List[str]:
     __lowerCAmelCase							     =     [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0]
     __lowerCAmelCase							     =     [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0]
     self.assertEqual(truncate_or_pad(lowerCAmelCase_ ,  self.block_size ,  0					) ,  lowerCAmelCase_					)






  def     lowercase		(    self			:		Any					)							->						Optional[Any]:
     __lowerCAmelCase							     =     [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3]
     __lowerCAmelCase							     =     [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0]
     self.assertEqual(truncate_or_pad(lowerCAmelCase_ ,  self.block_size ,  0					) ,  lowerCAmelCase_					)






  def     lowercase		(    self			:		List[str]					)							->						Any:
     __lowerCAmelCase							     =     'It was the year of Our Lord one thousand seven hundred and\n        seventy-five.\n\nSpiritual revelations were conceded to England at that\n        favoured period, as at this.'
     __lowerCAmelCase     ,     __lowerCAmelCase							     =     process_story(lowerCAmelCase_					)
     self.assertEqual(lowerCAmelCase_ ,  []					)






  def     lowercase		(    self			:		Any					)							->						str:
     __lowerCAmelCase							     =     ''
     __lowerCAmelCase     ,     __lowerCAmelCase							     =     process_story(lowerCAmelCase_					)
     self.assertEqual(lowerCAmelCase_ ,  []					)
     self.assertEqual(lowerCAmelCase_ ,  []					)






  def     lowercase		(    self			:		int					)							->						int:
     __lowerCAmelCase							     =     (
         'It was the year of Our Lord one thousand seven hundred and '
         'seventy-five\n\nSpiritual revelations were conceded to England '
         'at that favoured period, as at this.\n@highlight\n\nIt was the best of times'
     )
     __lowerCAmelCase     ,     __lowerCAmelCase							     =     process_story(lowerCAmelCase_					)

     __lowerCAmelCase							     =     [
         'It was the year of Our Lord one thousand seven hundred and seventy-five.',
         'Spiritual revelations were conceded to England at that favoured period, as at this.',
     ]
     self.assertEqual(lowerCAmelCase_ ,  lowerCAmelCase_					)

     __lowerCAmelCase							     =     ['It was the best of times.']
     self.assertEqual(lowerCAmelCase_ ,  lowerCAmelCase_					)






  def     lowercase		(    self			:		Dict					)							->						Any:
     __lowerCAmelCase							     =     torch.tensor([1, 2, 3, 4]					)
     __lowerCAmelCase							     =     torch.tensor([1, 1, 1, 1]					)
     np.testing.assert_array_equal(build_mask(lowerCAmelCase_ ,  0					).numpy() ,  expected.numpy()					)






  def     lowercase		(    self			:		List[Any]					)							->						Optional[int]:
     __lowerCAmelCase							     =     torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3]					)
     __lowerCAmelCase							     =     torch.tensor([1, 1, 1, 1, 0, 0, 0]					)
     np.testing.assert_array_equal(build_mask(lowerCAmelCase_ ,  2_3					).numpy() ,  expected.numpy()					)






  def     lowercase		(    self			:		str					)							->						List[Any]:
     __lowerCAmelCase							     =     torch.tensor([8, 2, 3, 4, 1, 1, 1]					)
     __lowerCAmelCase							     =     torch.tensor([1, 1, 1, 1, 0, 0, 0]					)
     np.testing.assert_array_equal(build_mask(lowerCAmelCase_ ,  1					).numpy() ,  expected.numpy()					)






  def     lowercase		(    self			:		Optional[Any]					)							->						Optional[int]:
     __lowerCAmelCase							     =     1_0_1
     __lowerCAmelCase							     =     torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]]					)
     __lowerCAmelCase							     =     torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]]					)

     __lowerCAmelCase							     =     compute_token_type_ids(lowerCAmelCase_ ,  lowerCAmelCase_					)
     np.testing.assert_array_equal(lowerCAmelCase_ ,  lowerCAmelCase_					)

