


'''simple docstring'''






import argparse
import os
import re

import tensorflow as tf
import torch

from transformers import BertConfig, BertModel
from transformers.utils import logging


logging.set_verbosity_info()
__A					:  str											=      logging.get_logger(__name__)







def 				UpperCamelCase_			(    A__					:   Dict							,    A__					:   Dict							,    A__					:   List[str]					):
  '''simple docstring'''





  lowerCAmelCase_			:      Any			=   os.path.abspath(A__					)
  logger.info(f'Converting TensorFlow checkpoint from {tf_path}'					)
  # Load weights from TF model
  lowerCAmelCase_			:      int			=   tf.train.list_variables(A__					)
  lowerCAmelCase_			:      List[Any]			=   []
  lowerCAmelCase_			:      Any			=   []
  lowerCAmelCase_			:      int			=   []
  for full_name, shape in init_vars:
    # logger.info(f"Loading TF weight {name} with shape {shape}")
    lowerCAmelCase_			:      List[str]			=   full_name.split("""/"""					)
    if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]:
      logger.info(f'Skipping non-model layer {full_name}'					)
      continue
    if "optimizer" in full_name:
      logger.info(f'Skipping optimization layer {full_name}'					)
      continue
    if name[0] == "model":
      # ignore initial 'model'
      lowerCAmelCase_			:      Dict			=   name[1:]
    # figure out how many levels deep the name is
    lowerCAmelCase_			:      Union[str, Any]			=   0
    for _name in name:
      if _name.startswith("""layer_with_weights"""					):
        depth += 1
      else:
        break
    layer_depth.append(A__					)
    # read data
    lowerCAmelCase_			:      str			=   tf.train.load_variable(A__							,    A__					)
    names.append("""/""".join(A__					)					)
    arrays.append(A__					)
  logger.info(f'Read a total of {len(A__					):,} layers'					)

  # Sanity check
  if len(set(A__					)					) != 1:
    raise ValueError(f'Found layer names with different depths (layer depth {list(set(A__					)					)})'					)
  lowerCAmelCase_			:      List[Any]			=   list(set(A__					)					)[0]
  if layer_depth != 1:
    raise ValueError(
        """The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP"""
        """ heads."""					)

  # convert layers
  logger.info("""Converting weights..."""					)
  for full_name, array in zip(A__							,    A__					):
    lowerCAmelCase_			:      List[str]			=   full_name.split("""/"""					)
    lowerCAmelCase_			:      Optional[int]			=   model
    lowerCAmelCase_			:      int			=   []
    for i, m_name in enumerate(A__					):
      if m_name == ".ATTRIBUTES":
        # variable names end with .ATTRIBUTES/VARIABLE_VALUE
        break
      if m_name.startswith("""layer_with_weights"""					):
        lowerCAmelCase_			:      List[str]			=   int(m_name.split("""-"""					)[-1]					)
        if layer_num <= 2:
          # embedding layers
          # layer_num 0: word_embeddings
          # layer_num 1: position_embeddings
          # layer_num 2: token_type_embeddings
          continue
        elif layer_num == 3:
          # embedding LayerNorm
          trace.extend(["""embeddings""", """LayerNorm"""]					)
          lowerCAmelCase_			:      Any			=   getattr(A__							,    """embeddings"""					)
          lowerCAmelCase_			:      Union[str, Any]			=   getattr(A__							,    """LayerNorm"""					)
        elif layer_num > 3 and layer_num < config.num_hidden_layers + 4:
          # encoder layers
          trace.extend(["""encoder""", """layer""", str(layer_num - 4					)]					)
          lowerCAmelCase_			:      Dict			=   getattr(A__							,    """encoder"""					)
          lowerCAmelCase_			:      Any			=   getattr(A__							,    """layer"""					)
          lowerCAmelCase_			:      Optional[int]			=   pointer[layer_num - 4]
        elif layer_num == config.num_hidden_layers + 4:
          # pooler layer
          trace.extend(["""pooler""", """dense"""]					)
          lowerCAmelCase_			:      List[Any]			=   getattr(A__							,    """pooler"""					)
          lowerCAmelCase_			:      List[str]			=   getattr(A__							,    """dense"""					)
      elif m_name == "embeddings":
        trace.append("""embeddings"""					)
        lowerCAmelCase_			:      Union[str, Any]			=   getattr(A__							,    """embeddings"""					)
        if layer_num == 0:
          trace.append("""word_embeddings"""					)
          lowerCAmelCase_			:      Union[str, Any]			=   getattr(A__							,    """word_embeddings"""					)
        elif layer_num == 1:
          trace.append("""position_embeddings"""					)
          lowerCAmelCase_			:      int			=   getattr(A__							,    """position_embeddings"""					)
        elif layer_num == 2:
          trace.append("""token_type_embeddings"""					)
          lowerCAmelCase_			:      Optional[Any]			=   getattr(A__							,    """token_type_embeddings"""					)
        else:
          raise ValueError(f'Unknown embedding layer with name {full_name}'					)
        trace.append("""weight"""					)
        lowerCAmelCase_			:      Union[str, Any]			=   getattr(A__							,    """weight"""					)
      elif m_name == "_attention_layer":
        # self-attention layer
        trace.extend(["""attention""", """self"""]					)
        lowerCAmelCase_			:      Any			=   getattr(A__							,    """attention"""					)
        lowerCAmelCase_			:      Optional[int]			=   getattr(A__							,    """self"""					)
      elif m_name == "_attention_layer_norm":
        # output attention norm
        trace.extend(["""attention""", """output""", """LayerNorm"""]					)
        lowerCAmelCase_			:      Optional[int]			=   getattr(A__							,    """attention"""					)
        lowerCAmelCase_			:      str			=   getattr(A__							,    """output"""					)
        lowerCAmelCase_			:      int			=   getattr(A__							,    """LayerNorm"""					)
      elif m_name == "_attention_output_dense":
        # output attention dense
        trace.extend(["""attention""", """output""", """dense"""]					)
        lowerCAmelCase_			:      Optional[Any]			=   getattr(A__							,    """attention"""					)
        lowerCAmelCase_			:      List[Any]			=   getattr(A__							,    """output"""					)
        lowerCAmelCase_			:      Any			=   getattr(A__							,    """dense"""					)
      elif m_name == "_output_dense":
        # output dense
        trace.extend(["""output""", """dense"""]					)
        lowerCAmelCase_			:      Tuple			=   getattr(A__							,    """output"""					)
        lowerCAmelCase_			:      Union[str, Any]			=   getattr(A__							,    """dense"""					)
      elif m_name == "_output_layer_norm":
        # output dense
        trace.extend(["""output""", """LayerNorm"""]					)
        lowerCAmelCase_			:      int			=   getattr(A__							,    """output"""					)
        lowerCAmelCase_			:      List[str]			=   getattr(A__							,    """LayerNorm"""					)
      elif m_name == "_key_dense":
        # attention key
        trace.append("""key"""					)
        lowerCAmelCase_			:      int			=   getattr(A__							,    """key"""					)
      elif m_name == "_query_dense":
        # attention query
        trace.append("""query"""					)
        lowerCAmelCase_			:      int			=   getattr(A__							,    """query"""					)
      elif m_name == "_value_dense":
        # attention value
        trace.append("""value"""					)
        lowerCAmelCase_			:      Optional[Any]			=   getattr(A__							,    """value"""					)
      elif m_name == "_intermediate_dense":
        # attention intermediate dense
        trace.extend(["""intermediate""", """dense"""]					)
        lowerCAmelCase_			:      Union[str, Any]			=   getattr(A__							,    """intermediate"""					)
        lowerCAmelCase_			:      str			=   getattr(A__							,    """dense"""					)
      elif m_name == "_output_layer_norm":
        # output layer norm
        trace.append("""output"""					)
        lowerCAmelCase_			:      Optional[Any]			=   getattr(A__							,    """output"""					)
      # weights & biases
      elif m_name in ["bias", "beta"]:
        trace.append("""bias"""					)
        lowerCAmelCase_			:      str			=   getattr(A__							,    """bias"""					)
      elif m_name in ["kernel", "gamma"]:
        trace.append("""weight"""					)
        lowerCAmelCase_			:      List[str]			=   getattr(A__							,    """weight"""					)
      else:
        logger.warning(f'Ignored {m_name}'					)
        # for certain layers reshape is necessary
    lowerCAmelCase_			:      Optional[Any]			=   """.""".join(A__					)
    if re.match(R"""(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)"""							,    A__					) or re.match(
        R"""(\S+)\.attention\.output\.dense\.weight"""							,    A__					):
      lowerCAmelCase_			:      Any			=   array.reshape(pointer.data.shape					)
    if "kernel" in full_name:
      lowerCAmelCase_			:      str			=   array.transpose()
    if pointer.shape == array.shape:
      lowerCAmelCase_			:      Any			=   torch.from_numpy(A__					)
    else:
      raise ValueError(
          f'Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:'
          f' {array.shape}'					)
    logger.info(f'Successfully set variable {full_name} to PyTorch layer {trace}'					)
  return model







def 				UpperCamelCase_			(    A__					:   List[Any]							,    A__					:   Any							,    A__					:   Dict					):
  '''simple docstring'''





  logger.info(f'Loading model based on config from {config_path}...'					)
  lowerCAmelCase_			:      str			=   BertConfig.from_json_file(A__					)
  lowerCAmelCase_			:      Optional[Any]			=   BertModel(A__					)

  # Load weights from checkpoint
  logger.info(f'Loading weights from checkpoint {tf_checkpoint_path}...'					)
  load_tfa_weights_in_bert(A__							,    A__							,    A__					)

  # Save pytorch-model
  logger.info(f'Saving PyTorch model to {pytorch_dump_path}...'					)
  torch.save(model.state_dict()							,    A__					)


if __name__ == "__main__":
  __A					:  List[Any]											=      argparse.ArgumentParser()
  parser.add_argument(
      "--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow 2.x checkpoint path."
  )
  parser.add_argument(
      "--bert_config_file",
      type=str,
      required=True,
      help="The config json file corresponding to the BERT model. This specifies the model architecture.",
  )
  parser.add_argument(
      "--pytorch_dump_path",
      type=str,
      required=True,
      help="Path to the output PyTorch model (must include filename).",
  )
  __A					:  List[str]											=      parser.parse_args()
  convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)







'''simple docstring'''






from sklearn.metrics import recall_score

import datasets


__A					:  Dict											=      "\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n"


__A					:  List[Any]											=      "\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n    - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.\n    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {'recall': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {'recall': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {'recall': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'recall': array([1., 0., 0.])}\n"


__A					:  str											=      "\n@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}\n"






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,_KWARGS_DESCRIPTION)
class    __snake_case       (   datasets.Metric):







    """simple docstring"""



    def __lowercase   (   self    :  str		)   ->  Dict:
      return datasets.MetricInfo(
          description=_DESCRIPTION    ,						citation=_CITATION    ,						inputs_description=_KWARGS_DESCRIPTION    ,						features=datasets.Features(
              {
                  """predictions""": datasets.Sequence(datasets.Value("""int32"""		)		),
                  """references""": datasets.Sequence(datasets.Value("""int32"""		)		),
              }
              if self.config_name == """multilabel"""
              else {
                  """predictions""": datasets.Value("""int32"""		),
                  """references""": datasets.Value("""int32"""		),
              }		)    ,						reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"""]    ,						)





    def __lowercase   (   self    :  Tuple    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Optional[Any]=None    ,						lowerCamelCase    :  Optional[int]=1    ,						lowerCamelCase    :  Union[str, Any]="binary"    ,						lowerCamelCase    :  Any=None    ,						lowerCamelCase    :  str="warn"    ,						)   ->  List[Any]:
      lowerCAmelCase_			:      Optional[int]			=   recall_score(
          lowerCamelCase    ,						lowerCamelCase    ,						labels=lowerCamelCase    ,						pos_label=lowerCamelCase    ,						average=lowerCamelCase    ,						sample_weight=lowerCamelCase    ,						zero_division=lowerCamelCase    ,						)
      return {"recall": float(lowerCamelCase		) if score.size == 1 else score}



