



import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


a_      :      str    =     logging.get_logger(__name__)


a_      :      str    =     R'\n    Args:\n        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n            or scores for each vocabulary token after SoftMax.\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional stopping criteria specific kwargs.\n\n    Return:\n        `bool`. `False` indicates we should continue, `True` indicates we should stop.\n\n'
class    __UpperCamelCase			(       _lowercase				):

 """simple docstring"""



 @add_start_docstrings(SCREAMING_SNAKE_CASE      )
 def __call__(	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      ) ->			bool:
  raise NotImplementedError('''StoppingCriteria needs to be subclassed'''      )





class    __UpperCamelCase			(       _lowercase				):

 """simple docstring"""



 def __init__(	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE = None      ) ->			Tuple:
  a__												= max_length
  a__												= max_position_embeddings



 @add_start_docstrings(SCREAMING_SNAKE_CASE      )
 def __call__(	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      ) ->			bool:
  a__												= input_ids.shape[-1]
  a__												= cur_len >= self.max_length
  if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
   logger.warning_once(
       '''This is a friendly reminder - the current text generation call will exceed the model\'s predefined '''
       f"maximum length ({self.max_position_embeddings}). Depending on the model, you may observe "
       '''exceptions, performance degradation, or nothing at all.'''      )
  return is_done





class    __UpperCamelCase			(       _lowercase				):

 """simple docstring"""



 def __init__(	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE      ) ->			str:
  warnings.warn(
      '''The class `MaxNewTokensCriteria` is deprecated. '''
      f"Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` "
      '''with `max_length = start_length + max_new_tokens` instead.'''		,				SCREAMING_SNAKE_CASE		,				)
  a__												= start_length
  a__												= max_new_tokens
  a__												= start_length + max_new_tokens



 @add_start_docstrings(SCREAMING_SNAKE_CASE      )
 def __call__(	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      ) ->			bool:
  return input_ids.shape[-1] >= self.max_length





class    __UpperCamelCase			(       _lowercase				):

 """simple docstring"""



 def __init__(	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE = None      ) ->			List[Any]:
  a__												= max_time
  a__												= time.time() if initial_timestamp is None else initial_timestamp



 @add_start_docstrings(SCREAMING_SNAKE_CASE      )
 def __call__(	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      ) ->			bool:
  return time.time() - self.initial_timestamp > self.max_time





class    __UpperCamelCase			(       _lowercase				):

 """simple docstring"""



 @add_start_docstrings(SCREAMING_SNAKE_CASE      )
 def __call__(	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				**SCREAMING_SNAKE_CASE      ) ->			bool:
  return any(criteria(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE      ) for criteria in self      )



 @property
 def 						_UpperCAmelCase       (	self      ) ->			Optional[int]:
  for stopping_criterium in self:
   if isinstance(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE      ):
    return stopping_criterium.max_length
   elif isinstance(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE      ):
    return stopping_criterium.max_length
  return None






def     __a					(		__UpperCAmelCase							,  __UpperCAmelCase       ):
 a__												= stopping_criteria.max_length
 a__												= deepcopy(__UpperCAmelCase       )
 if stopping_max_length is not None and stopping_max_length != max_length:
  warnings.warn('''You set different `max_length` for stopping criteria and `max_length` parameter'''							,  __UpperCAmelCase       )
 elif stopping_max_length is None:
  new_stopping_criteria.append(MaxLengthCriteria(max_length=__UpperCAmelCase       )       )
 return new_stopping_criteria










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
a_      :      Optional[int]    =     '.'

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






def     __a					(		__UpperCAmelCase							,  __UpperCAmelCase							,  __UpperCAmelCase       ):
 a__												= SavedModel()
 a__												= []

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

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

 with open(__UpperCAmelCase							,  '''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(__UpperCAmelCase       )
 a__												= []

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

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


if __name__ == "__main__":
     a_      :      Dict    =     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)'
     )
     a_      :      str    =     parser.parse_args()

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





