






'''simple docstring'''



import argparse
import json
import os

from tensorflow.core.protobuf.saved_model_pba import SavedModel


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_copies.py
__UpperCamelCase      :       int      			=      """."""

# Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model)
__UpperCamelCase      :       Optional[Any]      			=      [
    """Assert""",
    """AssignVariableOp""",
    """EmptyTensorList""",
    """MergeV2Checkpoints""",
    """ReadVariableOp""",
    """ResourceGather""",
    """RestoreV2""",
    """SaveV2""",
    """ShardedFilename""",
    """StatefulPartitionedCall""",
    """StaticRegexFullMatch""",
    """VarHandleOp""",
]



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Union[str, Any],					SCREAMING_SNAKE_CASE__:	Dict,					SCREAMING_SNAKE_CASE__:	Any    )  ->			Optional[int]:

   """simple docstring"""
   __a				     =    SavedModel()
   __a				     =    []

   with open(os.path.join(SCREAMING_SNAKE_CASE__,					'utils',					'tf_ops',					'onnx.json'    )    ) as f:
      __a				     =    json.load(SCREAMING_SNAKE_CASE__    )['opsets']

   for i in range(1,					opset + 1    ):
      onnx_ops.extend(onnx_opsets[str(SCREAMING_SNAKE_CASE__    )]    )

   with open(SCREAMING_SNAKE_CASE__,					'rb'    ) as f:
      saved_model.ParseFromString(f.read()    )

   __a				     =    set()

   # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs)
   for meta_graph in saved_model.meta_graphs:
      # Add operations in the graph definition
      model_op_names.update(node.op for node in meta_graph.graph_def.node    )

      # Go through the functions in the graph definition
      for func in meta_graph.graph_def.library.function:
         # Add operations in each function
         model_op_names.update(node.op for node in func.node_def    )

    # Convert to list, sorted if you want
   __a				     =    sorted(SCREAMING_SNAKE_CASE__    )
   __a				     =    []

   for op in model_op_names:
      if op not in onnx_ops and op not in INTERNAL_OPS:
         incompatible_ops.append(SCREAMING_SNAKE_CASE__    )

   if strict and len(SCREAMING_SNAKE_CASE__    ) > 0:
      raise Exception(f"""Found the following incompatible ops for the opset {opset}:\n""" + incompatible_ops    )
   elif len(SCREAMING_SNAKE_CASE__    ) > 0:
      print(f"""Found the following incompatible ops for the opset {opset}:"""    )
      print(*SCREAMING_SNAKE_CASE__,					sep='\n'    )
   else:
      print(f"""The saved model {saved_model_path} can properly be converted with ONNX."""    )


if __name__ == "__main__":
 __UpperCamelCase      :       List[str]      			=      argparse.ArgumentParser()
 parser.add_argument("""--saved_model_path""", help="""Path of the saved model to check (the .pb file).""")
 parser.add_argument(
     """--opset""", default=12, type=int, help="""The ONNX opset against which the model has to be tested."""
 )
 parser.add_argument(
     """--framework""", choices=["""onnx"""], default="""onnx""", help="""Frameworks against which to test the saved model."""
 )
 parser.add_argument(
     """--strict""", action="""store_true""", help="""Whether make the checking strict (raise errors) or not (raise warnings)"""
 )
 __UpperCamelCase      :       Union[str, Any]      			=      parser.parse_args()

 if args.framework == "onnx":
  onnx_compliancy(args.saved_model_path, args.strict, args.opset)














'''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 							__SCREAMING_SNAKE_CASE       (							nn.Module     ):




      def __init__(  self      )							->Dict:



         '''simple docstring'''
         super().__init__()
         __a				     =    nn.Linear(3 ,   4      )
         __a				     =    nn.BatchNormad(4      )
         __a				     =    nn.Linear(4 ,   5      )






      def  __UpperCamelCase							(  self ,   lowerCamelCase      )							->str:



         '''simple docstring'''
         return self.lineara(self.batchnorm(self.lineara(lowerCamelCase      )      )      )







class 							__SCREAMING_SNAKE_CASE       (							_lowerCAmelCase     ):




      def  __UpperCamelCase							(  self ,   lowerCamelCase ,   *lowerCamelCase ,   **lowerCamelCase      )							->str:



         '''simple docstring'''
         return (args[0] + 1,) + args[1:], kwargs







class 							__SCREAMING_SNAKE_CASE       (							_lowerCAmelCase     ):




      def  __UpperCamelCase							(  self ,   lowerCamelCase ,   lowerCamelCase      )							->int:



         '''simple docstring'''
         return output + 1







class 							__SCREAMING_SNAKE_CASE       (							unittest.TestCase     ):




      def  __UpperCamelCase							(  self      )							->Union[str, Any]:



         '''simple docstring'''
         __a				     =    ModelForTest()
         __a				     =    ModelHook()

         add_hook_to_module(lowerCamelCase ,   lowerCamelCase      )
         self.assertEqual(test_model._hf_hook ,   lowerCamelCase      )
         self.assertTrue(hasattr(lowerCamelCase ,   '_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(lowerCamelCase      )
         self.assertFalse(hasattr(lowerCamelCase ,   '_hf_hook'      )      )
         self.assertFalse(hasattr(lowerCamelCase ,   '_old_forward'      )      )




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         __a				     =    ModelForTest()
         __a				     =    ModelHook()

         add_hook_to_module(lowerCamelCase ,   lowerCamelCase      )
         add_hook_to_module(lowerCamelCase ,   lowerCamelCase ,   append=lowerCamelCase      )

         self.assertEqual(isinstance(test_model._hf_hook ,   lowerCamelCase      ) ,   lowerCamelCase      )
         self.assertEqual(len(test_model._hf_hook.hooks      ) ,   2      )
         self.assertTrue(hasattr(lowerCamelCase ,   '_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(lowerCamelCase      )
         self.assertFalse(hasattr(lowerCamelCase ,   '_hf_hook'      )      )
         self.assertFalse(hasattr(lowerCamelCase ,   '_old_forward'      )      )




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         __a				     =    ModelForTest()
         __a				     =    torch.randn(2 ,   3      )
         __a				     =    test_model(x + 1      )
         __a				     =    test_model(x + 2      )

         __a				     =    PreForwardHook()
         add_hook_to_module(lowerCamelCase ,   lowerCamelCase      )
         __a				     =    test_model(lowerCamelCase      )
         self.assertTrue(torch.allclose(lowerCamelCase ,   lowerCamelCase ,   atol=1e-5      )      )

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

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

         __a				     =    test_model(lowerCamelCase      )
         assert torch.allclose(lowerCamelCase ,   lowerCamelCase ,   atol=1e-5      )




      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         __a				     =    ModelForTest()
         __a				     =    torch.randn(2 ,   3      )
         __a				     =    test_model(lowerCamelCase      )

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

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

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

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




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         __a				     =    ModelForTest()
         __a				     =    torch.randn(2 ,   3      )
         __a				     =    test_model(lowerCamelCase      )

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

         __a				     =    True
         __a				     =    test_model(lowerCamelCase      )
         self.assertFalse(outputa.requires_grad      )




      @require_multi_gpu
      def  __UpperCamelCase							(  self      )							->Any:



         '''simple docstring'''
         __a				     =    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
         __a				     =    torch.randn(2 ,   3      )
         __a				     =    model(lowerCamelCase      )
         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(lowerCamelCase ,   AlignDevicesHook(io_same_device=lowerCamelCase      )      )
         __a				     =    torch.randn(2 ,   3      ).to(0      )
         __a				     =    model(lowerCamelCase      )
         self.assertEqual(output.device ,   torch.device(0      )      )




      def  __UpperCamelCase							(  self      )							->Any:



         '''simple docstring'''
         __a				     =    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
         __a				     =    {'execution_device': 0 if torch.cuda.is_available() else 'cpu', 'offload': True}

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

         # 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
         __a				     =    torch.device(hook_kwargs['execution_device']      )
         self.assertEqual(model.batchnorm.running_mean.device ,   lowerCamelCase      )

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

         # 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
         __a				     =    {
             'execution_device': 0 if torch.cuda.is_available() else 'cpu',
             'offload': True,
             'offload_buffers': True,
         }

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

         # 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'      )      )

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

         # 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  __UpperCamelCase							(  self      )							->List[Any]:



         '''simple docstring'''
         __a				     =    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
         __a				     =    0 if torch.cuda.is_available() else 'cpu'
         attach_align_device_hook(lowerCamelCase ,   execution_device=lowerCamelCase ,   offload=lowerCamelCase      )

         # 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
         __a				     =    torch.device(lowerCamelCase      )
         self.assertEqual(model.batchnorm.running_mean.device ,   lowerCamelCase      )

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

         # Removing hooks loads back the weights in the model.
         remove_hook_from_submodules(lowerCamelCase      )
         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(lowerCamelCase ,   execution_device=lowerCamelCase ,   offload=lowerCamelCase ,   offload_buffers=lowerCamelCase      )

         # 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'      )      )

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

         # Removing hooks loads back the weights in the model.
         remove_hook_from_submodules(lowerCamelCase      )
         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  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         __a				     =    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
         __a				     =    0 if torch.cuda.is_available() else 'cpu'
         attach_align_device_hook(
             lowerCamelCase ,   execution_device=lowerCamelCase ,   offload=lowerCamelCase ,   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
         __a				     =    torch.device(lowerCamelCase      )
         self.assertEqual(model.batchnorm.running_mean.device ,   lowerCamelCase      )

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

         # Removing hooks loads back the weights in the model.
         remove_hook_from_submodules(lowerCamelCase      )
         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(
             lowerCamelCase ,   execution_device=lowerCamelCase ,   offload=lowerCamelCase ,   weights_map=model.state_dict() ,   offload_buffers=lowerCamelCase ,   )

         # 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'      )      )

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

         # Removing hooks loads back the weights in the model.
         remove_hook_from_submodules(lowerCamelCase      )
         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'      )      )