


'''simple docstring'''
import numpy as np
from PIL import Image


def       _lowercase							(					UpperCamelCase__							:       np.ndarray,					UpperCamelCase__							:       int,					UpperCamelCase__							:       int      ):
 __A	:		int	  =      np.array(UpperCamelCase__      )
 if arr.shape[0] != arr.shape[1]:
  raise ValueError('The input array is not a square matrix'      )
 __A	:		int	  =      0
 __A	:		Optional[int]	  =      0
 __A	:		Union[str, Any]	  =      0
 __A	:		str	  =      0

 # compute the shape of the output matrix
 __A	:		Union[str, Any]	  =      (arr.shape[0] - size) // stride + 1
 # initialize the output matrix with zeros of shape maxpool_shape
 __A	:		Tuple	  =      np.zeros((maxpool_shape, maxpool_shape)      )

 while i < arr.shape[0]:
  if i + size > arr.shape[0]:
   # if the end of the matrix is reached, break
   break
  while j < arr.shape[1]:
   # if the end of the matrix is reached, break
   if j + size > arr.shape[1]:
    break
   # compute the maximum of the pooling matrix
   __A	:		int	  =      np.max(arr[i : i + size, j : j + size]      )
   # shift the pooling matrix by stride of column pixels
   j += stride
   mat_j += 1

  # shift the pooling matrix by stride of row pixels
  i += stride
  mat_i += 1

  # reset the column index to 0
  __A	:		Tuple	  =      0
  __A	:		List[str]	  =      0

 return updated_arr


def       _lowercase							(					UpperCamelCase__							:       np.ndarray,					UpperCamelCase__							:       int,					UpperCamelCase__							:       int      ):
 __A	:		Any	  =      np.array(UpperCamelCase__      )
 if arr.shape[0] != arr.shape[1]:
  raise ValueError('The input array is not a square matrix'      )
 __A	:		Union[str, Any]	  =      0
 __A	:		List[Any]	  =      0
 __A	:		Union[str, Any]	  =      0
 __A	:		List[Any]	  =      0

 # compute the shape of the output matrix
 __A	:		Optional[Any]	  =      (arr.shape[0] - size) // stride + 1
 # initialize the output matrix with zeros of shape avgpool_shape
 __A	:		str	  =      np.zeros((avgpool_shape, avgpool_shape)      )

 while i < arr.shape[0]:
  # if the end of the matrix is reached, break
  if i + size > arr.shape[0]:
   break
  while j < arr.shape[1]:
   # if the end of the matrix is reached, break
   if j + size > arr.shape[1]:
    break
   # compute the average of the pooling matrix
   __A	:		Optional[Any]	  =      int(np.average(arr[i : i + size, j : j + size]      )      )
   # shift the pooling matrix by stride of column pixels
   j += stride
   mat_j += 1

  # shift the pooling matrix by stride of row pixels
  i += stride
  mat_i += 1
  # reset the column index to 0
  __A	:		Any	  =      0
  __A	:		Optional[int]	  =      0

 return updated_arr


# Main Function
if __name__ == "__main__":
 from doctest import testmod

 testmod(name='avgpooling', verbose=True)

 # Loading the image
 UpperCAmelCase_			:  Any										=   Image.open('path_to_image')

 # Converting the image to numpy array and maxpooling, displaying the result
 # Ensure that the image is a square matrix

 Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()

 # Converting the image to numpy array and averagepooling, displaying the result
 # Ensure that the image is a square matrix

 Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()










'''simple docstring'''
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation

import warnings

from .state import AcceleratorState, GradientState


warnings.filterwarnings('ignore', category=UserWarning, module='torch.optim.lr_scheduler')

class     _lowerCamelCase       :




 '''simple docstring'''


 def __init__(   self   ,   __lowercase   ,   __lowercase   ,   __lowercase = True   ,   __lowercase = False    ):

  """simple docstring"""







  __A	:		List[str]	  =      scheduler
  __A	:		Dict	  =      optimizers if isinstance(__lowercase   ,   (list, tuple)    ) else [optimizers]
  __A	:		List[Any]	  =      split_batches
  __A	:		Any	  =      step_with_optimizer
  __A	:		List[Any]	  =      GradientState()


 def 			snake_case__ (   self   ,   *__lowercase   ,   **__lowercase    ):

  """simple docstring"""







  if not self.step_with_optimizer:
   # No link between scheduler and optimizer -> just step
   self.scheduler.step(*__lowercase   ,   **__lowercase    )
   return

  # Otherwise, first make sure the optimizer was stepped.
  if not self.gradient_state.sync_gradients:
   if self.gradient_state.adjust_scheduler:
    self.scheduler._step_count += 1
   return

  for opt in self.optimizers:
   if opt.step_was_skipped:
    return
  if self.split_batches:
   # Split batches -> the training dataloader batch size is not changed so one step per training step
   self.scheduler.step(*__lowercase   ,   **__lowercase    )
  else:
   # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
   # num_processes steps per training step
   __A	:		Tuple	  =      AcceleratorState().num_processes
   for _ in range(__lowercase    ):
    # Special case when using OneCycle and `drop_last` was not used
    if hasattr(self.scheduler   ,   'total_steps'    ):
     if self.scheduler._step_count <= self.scheduler.total_steps:
      self.scheduler.step(*__lowercase   ,   **__lowercase    )
    else:
     self.scheduler.step(*__lowercase   ,   **__lowercase    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  return self.scheduler.get_last_lr()


 def 			snake_case__ (   self    ):

  """simple docstring"""







  return self.scheduler.state_dict()


 def 			snake_case__ (   self   ,   __lowercase    ):

  """simple docstring"""







  self.scheduler.load_state_dict(__lowercase    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  return self.scheduler.get_lr()







 def 			snake_case__ (   self   ,   *__lowercase   ,   **__lowercase    ):

  """simple docstring"""







  return self.scheduler.print_lr(*__lowercase   ,   **__lowercase    )






