


"""simple docstring"""


def   snake_case		(     )   ->      list[list[int]]:
      return [list(range(1000 - i			,				-1000 - i			,				-1    )    ) for i in range(1000    )]


__lowerCamelCase      :List[str]	    =		generate_large_matrix()
__lowerCamelCase      :List[str]	    =		(
    [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
    [[3, 2], [1, 0]],
    [[7, 7, 6]],
    [[7, 7, 6], [-1, -2, -3]],
    grid,
)




def   snake_case		(     UpperCamelCase__       :						Tuple    )   ->      None:
      assert all(row == sorted(__snake_case			,				reverse=__snake_case    ) for row in grid    )
      assert all(list(__snake_case    ) == sorted(__snake_case			,				reverse=__snake_case    ) for col in zip(*__snake_case    )    )




def   snake_case		(     UpperCamelCase__       :						Tuple    )   ->      int:
      lowerCamelCase					:					Tuple        =	0
      lowerCamelCase					:					Optional[int]        =	len(__snake_case    ) - 1

      # Edge cases such as no values or all numbers are negative.
      if not array or array[0] < 0:
            return 0

      while right + 1 > left:
            lowerCamelCase					:					Any        =	(left + right) // 2
            lowerCamelCase					:					Optional[int]        =	array[mid]

            # Num must be negative and the index must be greater than or equal to 0.
            if num < 0 and array[mid - 1] >= 0:
                  return mid

            if num >= 0:
                  lowerCamelCase					:					Optional[Any]        =	mid + 1
            else:
                  lowerCamelCase					:					Optional[Any]        =	mid - 1
    # No negative numbers so return the last index of the array + 1 which is the length.
      return len(__snake_case    )




def   snake_case		(     UpperCamelCase__       :						List[Any]    )   ->      int:
      lowerCamelCase					:					int        =	0
      lowerCamelCase					:					Dict        =	len(grid[0]    )

      for i in range(len(__snake_case    )    ):
            lowerCamelCase					:					Optional[int]        =	find_negative_index(grid[i][:bound]    )
            total += bound
      return (len(__snake_case    ) * len(grid[0]    )) - total




def   snake_case		(     UpperCamelCase__       :						List[Any]    )   ->      int:
      return len([number for row in grid for number in row if number < 0]    )




def   snake_case		(     UpperCamelCase__       :						Union[str, Any]    )   ->      int:
      lowerCamelCase					:					Optional[int]        =	0
      for row in grid:
            for i, number in enumerate(__snake_case    ):
                  if number < 0:
                        total += len(__snake_case    ) - i
                        break
      return total




def   snake_case		(     )   ->      None:
      from timeit import timeit

      print("""Running benchmarks"""    )
      lowerCamelCase					:					int        =	(
          """from __main__ import count_negatives_binary_search, """
          """count_negatives_brute_force, count_negatives_brute_force_with_break, grid"""
      )
      for func in (
          "count_negatives_binary_search",  # took 0.7727 seconds
          "count_negatives_brute_force_with_break",  # took 4.6505 seconds
          "count_negatives_brute_force",  # took 12.8160 seconds
      ):
            lowerCamelCase					:					List[Any]        =	timeit(F'{func}(grid=grid)'			,				setup=__snake_case			,				number=500    )
            print(F'{func}() took {time:0.4f} seconds'    )


if __name__ == "__main__":
   import doctest

   doctest.testmod()
   benchmark()








"""simple docstring"""


import inspect
import unittest

import torch
import torch.nn as nn

from accelerate.hooks import (
    AlignDevicesHook,
    ModelHook,
    SequentialHook,
    add_hook_to_module,
    attach_align_device_hook,
    remove_hook_from_module,
    remove_hook_from_submodules,
)
from accelerate.test_utils import require_multi_gpu


class 			A__	(						nn.Module):


     """simple docstring"""

     def __init__(	self:						Dict	)->    Dict:
           super().__init__()
           lowerCamelCase					:					Tuple        =	nn.Linear(3     ,		4	)
           lowerCamelCase					:					Optional[Any]        =	nn.BatchNormad(4	)
           lowerCamelCase					:					Optional[Any]        =	nn.Linear(4     ,		5	)







     def 		a__						(	self:						List[str]     ,		__a:						List[Any]	)->    Optional[Any]:
           return self.lineara(self.batchnorm(self.lineara(__a	)	)	)


class 			A__	(						__lowercase):


     """simple docstring"""

     def 		a__						(	self:						Tuple     ,		__a:						int     ,		*__a:						Any     ,		**__a:						Tuple	)->    Tuple:
           return (args[0] + 1,) + args[1:], kwargs


class 			A__	(						__lowercase):


     """simple docstring"""

     def 		a__						(	self:						Optional[int]     ,		__a:						List[str]     ,		__a:						List[Any]	)->    List[str]:
           return output + 1


class 			A__	(						unittest.TestCase):


     """simple docstring"""

     def 		a__						(	self:						int	)->    str:
           lowerCamelCase					:					List[str]        =	ModelForTest()
           lowerCamelCase					:					Dict        =	ModelHook()

           add_hook_to_module(__a     ,		__a	)
           self.assertEqual(test_model._hf_hook     ,		__a	)
           self.assertTrue(hasattr(__a     ,		"""_old_forward"""	)	)

           # Check adding the hook did not change the name or the signature
           self.assertEqual(test_model.forward.__name__     ,		"""forward"""	)
           self.assertListEqual(list(inspect.signature(test_model.forward	).parameters	)     ,		["""x"""]	)

           remove_hook_from_module(__a	)
           self.assertFalse(hasattr(__a     ,		"""_hf_hook"""	)	)
           self.assertFalse(hasattr(__a     ,		"""_old_forward"""	)	)

     def 		a__						(	self:						int	)->    str:
           lowerCamelCase					:					List[str]        =	ModelForTest()
           lowerCamelCase					:					Union[str, Any]        =	ModelHook()

           add_hook_to_module(__a     ,		__a	)
           add_hook_to_module(__a     ,		__a     ,		append=__a	)

           self.assertEqual(isinstance(test_model._hf_hook     ,		__a	)     ,		__a	)
           self.assertEqual(len(test_model._hf_hook.hooks	)     ,		2	)
           self.assertTrue(hasattr(__a     ,		"""_old_forward"""	)	)

           # Check adding the hook did not change the name or the signature
           self.assertEqual(test_model.forward.__name__     ,		"""forward"""	)
           self.assertListEqual(list(inspect.signature(test_model.forward	).parameters	)     ,		["""x"""]	)

           remove_hook_from_module(__a	)
           self.assertFalse(hasattr(__a     ,		"""_hf_hook"""	)	)
           self.assertFalse(hasattr(__a     ,		"""_old_forward"""	)	)

     def 		a__						(	self:						List[Any]	)->    List[str]:
           lowerCamelCase					:					str        =	ModelForTest()
           lowerCamelCase					:					Dict        =	torch.randn(2     ,		3	)
           lowerCamelCase					:					Union[str, Any]        =	test_model(x + 1	)
           lowerCamelCase					:					Optional[int]        =	test_model(x + 2	)

           lowerCamelCase					:					List[Any]        =	PreForwardHook()
           add_hook_to_module(__a     ,		__a	)
           lowerCamelCase					:					Optional[int]        =	test_model(__a	)
           self.assertTrue(torch.allclose(__a     ,		__a     ,		atol=1e-5	)	)

           # Attaching a hook to a model when it already has one replaces, does not chain
           lowerCamelCase					:					Dict        =	PreForwardHook()
           add_hook_to_module(__a     ,		__a	)
           lowerCamelCase					:					Tuple        =	test_model(__a	)
           self.assertTrue(torch.allclose(__a     ,		__a     ,		atol=1e-5	)	)

           # You need to use the sequential hook to chain two or more hooks
           lowerCamelCase					:					Any        =	SequentialHook(PreForwardHook()     ,		PreForwardHook()	)
           add_hook_to_module(__a     ,		__a	)

           lowerCamelCase					:					Optional[Any]        =	test_model(__a	)
           assert torch.allclose(__a     ,		__a     ,		atol=1e-5	)

     def 		a__						(	self:						Any	)->    Optional[int]:
           lowerCamelCase					:					str        =	ModelForTest()
           lowerCamelCase					:					List[str]        =	torch.randn(2     ,		3	)
           lowerCamelCase					:					int        =	test_model(__a	)

           lowerCamelCase					:					Dict        =	PostForwardHook()
           add_hook_to_module(__a     ,		__a	)
           lowerCamelCase					:					Tuple        =	test_model(__a	)
           self.assertTrue(torch.allclose(__a     ,		output + 1     ,		atol=1e-5	)	)

           # Attaching a hook to a model when it already has one replaces, does not chain
           lowerCamelCase					:					str        =	PostForwardHook()
           add_hook_to_module(__a     ,		__a	)
           lowerCamelCase					:					Optional[Any]        =	test_model(__a	)
           self.assertTrue(torch.allclose(__a     ,		output + 1     ,		atol=1e-5	)	)

           # You need to use the sequential hook to chain two or more hooks
           lowerCamelCase					:					Union[str, Any]        =	SequentialHook(PostForwardHook()     ,		PostForwardHook()	)
           add_hook_to_module(__a     ,		__a	)

           lowerCamelCase					:					str        =	test_model(__a	)
           assert torch.allclose(__a     ,		output + 2     ,		atol=1e-5	)

     def 		a__						(	self:						int	)->    Dict:
           lowerCamelCase					:					List[Any]        =	ModelForTest()
           lowerCamelCase					:					Optional[int]        =	torch.randn(2     ,		3	)
           lowerCamelCase					:					List[str]        =	test_model(__a	)

           lowerCamelCase					:					Any        =	PostForwardHook()
           add_hook_to_module(__a     ,		__a	)
           lowerCamelCase					:					str        =	test_model(__a	)
           self.assertTrue(torch.allclose(__a     ,		output + 1	)	)
           self.assertTrue(outputa.requires_grad	)

           lowerCamelCase					:					Optional[int]        =	True
           lowerCamelCase					:					Optional[int]        =	test_model(__a	)
           self.assertFalse(outputa.requires_grad	)

     @require_multi_gpu
     def 		a__						(	self:						List[str]	)->    Union[str, Any]:
           lowerCamelCase					:					int        =	ModelForTest()
           # Everything is on CPU
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)

           # This will move each submodule on different devices
           add_hook_to_module(model.lineara     ,		AlignDevicesHook(execution_device=0	)	)
           add_hook_to_module(model.batchnorm     ,		AlignDevicesHook(execution_device=0	)	)
           add_hook_to_module(model.lineara     ,		AlignDevicesHook(execution_device=1	)	)

           self.assertEqual(model.lineara.weight.device     ,		torch.device(0	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device(0	)	)
           self.assertEqual(model.batchnorm.running_mean.device     ,		torch.device(0	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device(1	)	)

           # We can still make a forward pass. The input does not need to be on any particular device
           lowerCamelCase					:					str        =	torch.randn(2     ,		3	)
           lowerCamelCase					:					Dict        =	model(__a	)
           self.assertEqual(output.device     ,		torch.device(1	)	)

           # We can add a general hook to put back output on same device as input.
           add_hook_to_module(__a     ,		AlignDevicesHook(io_same_device=__a	)	)
           lowerCamelCase					:					Optional[int]        =	torch.randn(2     ,		3	).to(0	)
           lowerCamelCase					:					str        =	model(__a	)
           self.assertEqual(output.device     ,		torch.device(0	)	)

     def 		a__						(	self:						List[str]	)->    Tuple:
           lowerCamelCase					:					Union[str, Any]        =	ModelForTest()

           # Everything is on CPU
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)

           # This will move each submodule on different devices
           lowerCamelCase					:					Tuple        =	{"""execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True}

           add_hook_to_module(model.lineara     ,		AlignDevicesHook(**__a	)	)
           add_hook_to_module(model.batchnorm     ,		AlignDevicesHook(**__a	)	)
           add_hook_to_module(model.lineara     ,		AlignDevicesHook(**__a	)	)

           # Parameters have been offloaded, so on the meta device
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           # Buffers are not included in the offload by default, so are on the execution device
           lowerCamelCase					:					List[Any]        =	torch.device(hook_kwargs["""execution_device"""]	)
           self.assertEqual(model.batchnorm.running_mean.device     ,		__a	)

           lowerCamelCase					:					Optional[Any]        =	torch.randn(2     ,		3	)
           lowerCamelCase					:					Optional[Any]        =	model(__a	)
           self.assertEqual(output.device     ,		__a	)

           # Removing hooks loads back the weights in the model.
           remove_hook_from_module(model.lineara	)
           remove_hook_from_module(model.batchnorm	)
           remove_hook_from_module(model.lineara	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)

           # Now test with buffers included in the offload
           lowerCamelCase					:					Any        =	{
               """execution_device""": 0 if torch.cuda.is_available() else """cpu""",
               """offload""": True,
               """offload_buffers""": True,
           }

           add_hook_to_module(model.lineara     ,		AlignDevicesHook(**__a	)	)
           add_hook_to_module(model.batchnorm     ,		AlignDevicesHook(**__a	)	)
           add_hook_to_module(model.lineara     ,		AlignDevicesHook(**__a	)	)

           # Parameters have been offloaded, so on the meta device, buffers included
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.batchnorm.running_mean.device     ,		torch.device("""meta"""	)	)

           lowerCamelCase					:					int        =	torch.randn(2     ,		3	)
           lowerCamelCase					:					Optional[int]        =	model(__a	)
           self.assertEqual(output.device     ,		__a	)

           # Removing hooks loads back the weights in the model.
           remove_hook_from_module(model.lineara	)
           remove_hook_from_module(model.batchnorm	)
           remove_hook_from_module(model.lineara	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)

     def 		a__						(	self:						Any	)->    List[str]:
           lowerCamelCase					:					int        =	ModelForTest()

           # Everything is on CPU
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)

           # This will move each submodule on different devices
           lowerCamelCase					:					int        =	0 if torch.cuda.is_available() else """cpu"""
           attach_align_device_hook(__a     ,		execution_device=__a     ,		offload=__a	)

           # Parameters have been offloaded, so on the meta device
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           # Buffers are not included in the offload by default, so are on the execution device
           lowerCamelCase					:					List[Any]        =	torch.device(__a	)
           self.assertEqual(model.batchnorm.running_mean.device     ,		__a	)

           lowerCamelCase					:					Dict        =	torch.randn(2     ,		3	)
           lowerCamelCase					:					Optional[Any]        =	model(__a	)
           self.assertEqual(output.device     ,		__a	)

           # Removing hooks loads back the weights in the model.
           remove_hook_from_submodules(__a	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)

           # Now test with buffers included in the offload
           attach_align_device_hook(__a     ,		execution_device=__a     ,		offload=__a     ,		offload_buffers=__a	)

           # Parameters have been offloaded, so on the meta device, buffers included
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.batchnorm.running_mean.device     ,		torch.device("""meta"""	)	)

           lowerCamelCase					:					Optional[int]        =	torch.randn(2     ,		3	)
           lowerCamelCase					:					int        =	model(__a	)
           self.assertEqual(output.device     ,		__a	)

           # Removing hooks loads back the weights in the model.
           remove_hook_from_submodules(__a	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)







     def 		a__						(	self:						Optional[Any]	)->    List[Any]:
           lowerCamelCase					:					List[Any]        =	ModelForTest()

           # Everything is on CPU
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)

           # This will move each submodule on different devices
           lowerCamelCase					:					Any        =	0 if torch.cuda.is_available() else """cpu"""
           attach_align_device_hook(
               __a     ,		execution_device=__a     ,		offload=__a     ,		weights_map=model.state_dict()	)

           # Parameters have been offloaded, so on the meta device
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           # Buffers are not included in the offload by default, so are on the execution device
           lowerCamelCase					:					List[Any]        =	torch.device(__a	)
           self.assertEqual(model.batchnorm.running_mean.device     ,		__a	)

           lowerCamelCase					:					Dict        =	torch.randn(2     ,		3	)
           lowerCamelCase					:					int        =	model(__a	)
           self.assertEqual(output.device     ,		__a	)

           # Removing hooks loads back the weights in the model.
           remove_hook_from_submodules(__a	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)

           # Now test with buffers included in the offload
           attach_align_device_hook(
               __a     ,		execution_device=__a     ,		offload=__a     ,		weights_map=model.state_dict()     ,		offload_buffers=__a     ,		)

           # Parameters have been offloaded, so on the meta device, buffers included
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""meta"""	)	)
           self.assertEqual(model.batchnorm.running_mean.device     ,		torch.device("""meta"""	)	)

           lowerCamelCase					:					Tuple        =	torch.randn(2     ,		3	)
           lowerCamelCase					:					Any        =	model(__a	)
           self.assertEqual(output.device     ,		__a	)

           # Removing hooks loads back the weights in the model.
           remove_hook_from_submodules(__a	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.batchnorm.weight.device     ,		torch.device("""cpu"""	)	)
           self.assertEqual(model.lineara.weight.device     ,		torch.device("""cpu"""	)	)




