



from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


_snake_case	=						logging.get_logger(__name__)






def        A       (      _lowerCamelCase						):





							'''simple docstring'''




							if isinstance(_lowerCamelCase       ,				np.ndarray						):
														return list(tensor.shape						)

							_lowerCAmelCase  :							Optional[int]				     =					tf.shape(_lowerCamelCase						)

							if tensor.shape == tf.TensorShape(_lowerCamelCase						):
														return dynamic

							_lowerCAmelCase  :							List[Any]				     =					tensor.shape.as_list()

							return [dynamic[i] if s is None else s for i, s in enumerate(_lowerCamelCase						)]






def        A       (      _lowerCamelCase       ,				_lowerCamelCase = None       ,				_lowerCamelCase = None						):





							'''simple docstring'''




							return tf.nn.softmax(logits=logits + 1e-9       ,				axis=_lowerCamelCase       ,				name=_lowerCamelCase						)






def        A       (      _lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase=1e-5       ,				_lowerCamelCase=-1						):





							'''simple docstring'''




							if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(_lowerCamelCase       ,				_lowerCamelCase						):
														raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis."						)

							# Get mean and variance on the axis to be normalized
							_lowerCAmelCase  :							str				     =					tf.nn.moments(_lowerCamelCase       ,				axes=[axis]       ,				keepdims=_lowerCamelCase						)

							if axis != -1:
														# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
														# on every dimension except axis
														_lowerCAmelCase  :							Dict				     =					[1] * inputs.shape.rank
														_lowerCAmelCase  :							List[Any]				     =					shape_list(_lowerCamelCase						)[axis]
														_lowerCAmelCase  :							Optional[Any]				     =					tf.reshape(_lowerCamelCase       ,				_lowerCamelCase						)
														_lowerCAmelCase  :							Dict				     =					tf.reshape(_lowerCamelCase       ,				_lowerCamelCase						)

							# Compute layer normalization using the batch_normalization
							# function.
							_lowerCAmelCase  :							Union[str, Any]				     =					tf.nn.batch_normalization(
							    _lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase       ,				offset=_lowerCamelCase       ,				scale=_lowerCamelCase       ,				variance_epsilon=_lowerCamelCase       ,				)
							return outputs






def        A       (      _lowerCamelCase       ,				_lowerCamelCase=0       ,				_lowerCamelCase=-1						):





							'''simple docstring'''




							if end_dim < 0:
														end_dim += input.shape.rank
							if start_dim < 0:
														start_dim += input.shape.rank

							if start_dim == end_dim:
														return input

							_lowerCAmelCase  :							Dict				     =					tf.shape(_lowerCamelCase						)
							_lowerCAmelCase  :							List[Any]				     =					tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]						)
							_lowerCAmelCase  :							Optional[int]				     =					tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]       ,				axis=0						)
							return tf.reshape(_lowerCamelCase       ,				_lowerCamelCase						)






def        A       (      _lowerCamelCase						):





							'''simple docstring'''




							if not isinstance(_lowerCamelCase       ,				tf.Tensor						):
														_lowerCAmelCase  :							Tuple				     =					tf.convert_to_tensor(_lowerCamelCase						)  # Catches stray NumPy inputs
							if encoder_attention_mask.shape.rank == 3:
														_lowerCAmelCase  :							Dict				     =					encoder_attention_mask[:, None, :, :]
							if encoder_attention_mask.shape.rank == 2:
														_lowerCAmelCase  :							Optional[int]				     =					encoder_attention_mask[:, None, None, :]
							# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
							# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
							# /transformer/transformer_layers.py#L270
							# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
							# encoder_extended_attention_mask.transpose(-1, -2))
							_lowerCAmelCase  :							int				     =					(
							    tf.cast(1       ,				encoder_attention_mask.dtype						) - encoder_extended_attention_mask
							) * encoder_extended_attention_mask.dtype.min

							return encoder_extended_attention_mask






def        A       (      _lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase = "input_ids"						):





							'''simple docstring'''




							tf.debugging.assert_less(
							    _lowerCamelCase       ,				tf.cast(_lowerCamelCase       ,				dtype=tensor.dtype						)       ,				message=(
							        F"The maximum value of {tensor_name} ({tf.math.reduce_max(_lowerCamelCase						)}) must be smaller than the embedding "
							        F"layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time."
							    )       ,				)






def        A       (      _lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase						):





							'''simple docstring'''




							_lowerCAmelCase  :							Union[str, Any]				     =					64_512
							# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
							# because in that case even chunking the array would not make the saving
							# possible.
							_lowerCAmelCase  :							Optional[int]				     =					[x for x in data if len(_lowerCamelCase						) > HDF5_OBJECT_HEADER_LIMIT]

							# Expecting this to never be true.
							if bad_attributes:
														raise RuntimeError(
														    "The following attributes cannot be saved to HDF5 file because "
														    F"they are larger than {HDF5_OBJECT_HEADER_LIMIT} "
														    F"bytes: {bad_attributes}"						)

							_lowerCAmelCase  :							Dict				     =					np.asarray(_lowerCamelCase						)

							_lowerCAmelCase  :							Optional[Any]				     =					1
							_lowerCAmelCase  :							str				     =					np.array_split(_lowerCamelCase       ,				_lowerCamelCase						)

							# This will never loop forever thanks to the test above.
							while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data						):
														num_chunks += 1
														_lowerCAmelCase  :							Union[str, Any]				     =					np.array_split(_lowerCamelCase       ,				_lowerCamelCase						)

							if num_chunks > 1:
														for chunk_id, chunk_data in enumerate(_lowerCamelCase						):
																					_lowerCAmelCase  :							List[Any]				     =					chunk_data
							else:
														_lowerCAmelCase  :							List[str]				     =					data






def        A       (      _lowerCamelCase       ,				_lowerCamelCase						):





							'''simple docstring'''




							if name in group.attrs:
														_lowerCAmelCase  :							Tuple				     =					[n.decode("utf8"						) if hasattr(_lowerCamelCase       ,				"decode"						) else n for n in group.attrs[name]]
							else:
														_lowerCAmelCase  :							List[str]				     =					[]
														_lowerCAmelCase  :							Dict				     =					0
														while "%s%d" % (name, chunk_id) in group.attrs:
																					data.extend(
																					    [n.decode("utf8"						) if hasattr(_lowerCamelCase       ,				"decode"						) else n for n in group.attrs["%s%d" % (name, chunk_id)]]						)
																					chunk_id += 1
							return data






def        A       (      _lowerCamelCase						):





							'''simple docstring'''




							def _expand_single_ad_tensor(_lowerCamelCase						):
														if isinstance(_lowerCamelCase       ,				tf.Tensor						) and t.shape.rank == 1:
																					return tf.expand_dims(_lowerCamelCase       ,				axis=-1						)
														return t

							return tf.nest.map_structure(_expand_single_ad_tensor       ,				_lowerCamelCase						)





import argparse
import os

import torch

from transformers import (
    XLNetConfig,
    XLNetForQuestionAnswering,
    XLNetForSequenceClassification,
    XLNetLMHeadModel,
    load_tf_weights_in_xlnet,
)
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


_snake_case	=						{
    "cola": 2,
    "mnli": 3,
    "mrpc": 2,
    "sst-2": 2,
    "sts-b": 1,
    "qqp": 2,
    "qnli": 2,
    "rte": 2,
    "wnli": 2,
}


logging.set_verbosity_info()






def        A       (      _lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase=None						):





							'''simple docstring'''




							_lowerCAmelCase  :							Optional[Any]				     =					XLNetConfig.from_json_file(_lowerCamelCase						)

							_lowerCAmelCase  :							Any				     =					finetuning_task.lower() if finetuning_task is not None else ""
							if finetuning_task in GLUE_TASKS_NUM_LABELS:
														print(F"Building PyTorch XLNetForSequenceClassification model from configuration: {config}"						)
														_lowerCAmelCase  :							Any				     =					finetuning_task
														_lowerCAmelCase  :							Any				     =					GLUE_TASKS_NUM_LABELS[finetuning_task]
														_lowerCAmelCase  :							Union[str, Any]				     =					XLNetForSequenceClassification(_lowerCamelCase						)
							elif "squad" in finetuning_task:
														_lowerCAmelCase  :							Union[str, Any]				     =					finetuning_task
														_lowerCAmelCase  :							Any				     =					XLNetForQuestionAnswering(_lowerCamelCase						)
							else:
														_lowerCAmelCase  :							Union[str, Any]				     =					XLNetLMHeadModel(_lowerCamelCase						)

							# Load weights from tf checkpoint
							load_tf_weights_in_xlnet(_lowerCamelCase       ,				_lowerCamelCase       ,				_lowerCamelCase						)

							# Save pytorch-model
							_lowerCAmelCase  :							Optional[int]				     =					os.path.join(_lowerCamelCase       ,				_lowerCamelCase						)
							_lowerCAmelCase  :							Dict				     =					os.path.join(_lowerCamelCase       ,				_lowerCamelCase						)
							print(F"Save PyTorch model to {os.path.abspath(_lowerCamelCase						)}"						)
							torch.save(model.state_dict()       ,				_lowerCamelCase						)
							print(F"Save configuration file to {os.path.abspath(_lowerCamelCase						)}"						)
							with open(_lowerCamelCase       ,				"w"       ,				encoding="utf-8"						) as f:
														f.write(config.to_json_string()						)


if __name__ == "__main__":
						_snake_case	=						argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
						)
						parser.add_argument(
						    "--xlnet_config_file",
						    default=None,
						    type=str,
						    required=True,
						    help=(
						        "The config json file corresponding to the pre-trained XLNet model. \n"
						        "This specifies the model architecture."
						    ),
						)
						parser.add_argument(
						    "--pytorch_dump_folder_path",
						    default=None,
						    type=str,
						    required=True,
						    help="Path to the folder to store the PyTorch model or dataset/vocab.",
						)
						parser.add_argument(
						    "--finetuning_task",
						    default=None,
						    type=str,
						    help="Name of a task on which the XLNet TensorFlow model was fine-tuned",
						)
						_snake_case	=						parser.parse_args()
						print(args)

						convert_xlnet_checkpoint_to_pytorch(
						    args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task
						)
