



"""simple docstring"""


import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
__A   :							Tuple										=   pytest.mark.integration


__A   :							List[Any]										=   {"comet"}
__A   :							Optional[Any]										=   importlib.util.find_spec("fairseq") is not None

__A   :							Dict										=   {"code_eval"}
__A   :							Union[str, Any]										=   os.name == "nt"

__A   :							Union[str, Any]										=   {"bertscore", "frugalscore", "perplexity"}
__A   :							Dict										=   importlib.util.find_spec("transformers") is not None







def  lowercase	(      _SCREAMING_SNAKE_CASE   :						Any				):






				'''simple docstring'''



				@wraps(__lowerCAmelCase				)
				def wrapper(self   :						int					,     _SCREAMING_SNAKE_CASE   :						List[str]				):
								if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
												self.skipTest('''\"test requires Fairseq\"'''				)
								else:
												test_case(self					,     __lowerCAmelCase				)

				return wrapper







def  lowercase	(      _SCREAMING_SNAKE_CASE   :						Union[str, Any]				):






				'''simple docstring'''



				@wraps(__lowerCAmelCase				)
				def wrapper(self   :						int					,     _SCREAMING_SNAKE_CASE   :						Any				):
								if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
												self.skipTest('''\"test requires transformers\"'''				)
								else:
												test_case(self					,     __lowerCAmelCase				)

				return wrapper







def  lowercase	(      _SCREAMING_SNAKE_CASE   :						List[Any]				):






				'''simple docstring'''



				@wraps(__lowerCAmelCase				)
				def wrapper(self   :						Union[str, Any]					,     _SCREAMING_SNAKE_CASE   :						Optional[int]				):
								if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
												self.skipTest('''\"test not supported on Windows\"'''				)
								else:
												test_case(self					,     __lowerCAmelCase				)

				return wrapper







def  lowercase	(      ):






				'''simple docstring'''



				_UpperCAmelCase					=    [metric_dir.split(os.sep				)[-2] for metric_dir in glob.glob('''./metrics/*/'''				)]
				return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished
@parameterized.named_parameters(get_local_metric_names())
@for_all_test_methods(
    UpperCamelCase_			,							UpperCamelCase_			,							UpperCamelCase_)
@local
class 			_a (					parameterized.TestCase):
			"""simple docstring"""
			UpperCamelCase__			      =	{}
			UpperCamelCase__			      =	None



			@pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning'''   )
			@pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning'''   )
			def  lowercase__						(		self     :    Dict				,   __UpperCamelCase     :    List[Any]   )->Any:
							_UpperCAmelCase					=    """[...]"""
							_UpperCAmelCase					=    importlib.import_module(
							    datasets.load.metric_module_factory(os.path.join('''metrics'''				,   _a   )   ).module_path   )
							_UpperCAmelCase					=    datasets.load.import_main_class(metric_module.__name__				,   dataset=_a   )
							# check parameters
							_UpperCAmelCase					=    inspect.signature(metric._compute   ).parameters
							self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()   )   )  # no **kwargs
							# run doctest
							with self.patch_intensive_calls(_a				,   metric_module.__name__   ):
											with self.use_local_metrics():
															try:
																			_UpperCAmelCase					=    doctest.testmod(_a				,   verbose=_a				,   raise_on_error=_a   )
															except doctest.UnexpectedException as e:
																			raise e.exc_info[1]  # raise the exception that doctest caught
							self.assertEqual(results.failed				,   0   )
							self.assertGreater(results.attempted				,   1   )



			@slow
			def  lowercase__						(		self     :    str				,   __UpperCamelCase     :    List[str]   )->Any:
							_UpperCAmelCase					=    """[...]"""
							_UpperCAmelCase					=    importlib.import_module(
							    datasets.load.metric_module_factory(os.path.join('''metrics'''				,   _a   )   ).module_path   )
							# run doctest
							with self.use_local_metrics():
											_UpperCAmelCase					=    doctest.testmod(_a				,   verbose=_a				,   raise_on_error=_a   )
							self.assertEqual(results.failed				,   0   )
							self.assertGreater(results.attempted				,   1   )



			@contextmanager
			def  lowercase__						(		self     :    str				,   __UpperCamelCase     :    Dict				,   __UpperCamelCase     :    Optional[int]   )->Dict:


							if metric_name in self.INTENSIVE_CALLS_PATCHER:
											with self.INTENSIVE_CALLS_PATCHER[metric_name](_a   ):
															yield
							else:
											yield



			@contextmanager
			def  lowercase__						(		self     :    Tuple   )->List[str]:


							def load_local_metric(__UpperCamelCase     :    Optional[int]				,   *__UpperCamelCase     :    Optional[Any]				,   **__UpperCamelCase     :    str   ):
											return load_metric(os.path.join('''metrics'''				,   _a   )				,   *_a				,   **_a   )

							with patch('''datasets.load_metric'''   ) as mock_load_metric:
											_UpperCAmelCase					=    load_local_metric
											yield



			@classmethod
			def  lowercase__						(		cls     :    Optional[Any]				,   __UpperCamelCase     :    str   )->Dict:


							def wrapper(__UpperCamelCase     :    Tuple   ):
											_UpperCAmelCase					=    contextmanager(_a   )
											_UpperCAmelCase					=    patcher
											return patcher

							return wrapper







@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''				)
def  lowercase	(      _SCREAMING_SNAKE_CASE   :						Any				):






				'''simple docstring'''



				import tensorflow.compat.va as tf
				from bleurt.score import Predictor

				tf.flags.DEFINE_string('''sv'''					,     ''''''					,     ''''''				)  # handle pytest cli flags
				class 			_a (					UpperCamelCase_):
							"""simple docstring"""



							def  lowercase__						(		self     :    Optional[Any]				,   __UpperCamelCase     :    Tuple   )->Optional[Any]:
											assert len(input_dict['''input_ids''']   ) == 2
											return np.array([1.0_3, 1.0_4]   )

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
				with patch('''bleurt.score._create_predictor'''				) as mock_create_predictor:
								_UpperCAmelCase					=    MockedPredictor()
								yield







@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''				)
def  lowercase	(      _SCREAMING_SNAKE_CASE   :						Optional[int]				):






				'''simple docstring'''



				import torch

				def bert_cos_score_idf(_SCREAMING_SNAKE_CASE   :						List[str]					,     _SCREAMING_SNAKE_CASE   :						List[str]					,     *_SCREAMING_SNAKE_CASE   :						int					,     **_SCREAMING_SNAKE_CASE   :						str				):
								return torch.tensor([[1.0, 1.0, 1.0]] * len(__lowerCAmelCase				)				)

				# mock get_model which is supposed to do download a bert model
				# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
				with patch('''bert_score.scorer.get_model'''				), patch(
				    '''bert_score.scorer.bert_cos_score_idf'''				) as mock_bert_cos_score_idf:
								_UpperCAmelCase					=    bert_cos_score_idf
								yield







@LocalMetricTest.register_intensive_calls_patcher('''comet'''				)
def  lowercase	(      _SCREAMING_SNAKE_CASE   :						int				):






				'''simple docstring'''



				def load_from_checkpoint(_SCREAMING_SNAKE_CASE   :						Any				):
								class 			_a :
											"""simple docstring"""



											def  lowercase__						(		self     :    Tuple				,   __UpperCamelCase     :    Tuple				,   *__UpperCamelCase     :    Tuple				,   **__UpperCamelCase     :    List[Any]   )->Dict:
															assert len(_a   ) == 2
															_UpperCAmelCase					=    [0.1_9, 0.9_2]
															return scores, sum(_a   ) / len(_a   )



								return Model()

				# mock load_from_checkpoint which is supposed to do download a bert model
				# mock load_from_checkpoint which is supposed to do download a bert model
				with patch('''comet.download_model'''				) as mock_download_model:
								_UpperCAmelCase					=    None
								with patch('''comet.load_from_checkpoint'''				) as mock_load_from_checkpoint:
												_UpperCAmelCase					=    load_from_checkpoint
												yield







def  lowercase	(      ):






				'''simple docstring'''



				_UpperCAmelCase					=    load_metric(os.path.join('''metrics'''					,     '''seqeval'''				)				)
				_UpperCAmelCase					=    """ERROR"""
				_UpperCAmelCase					=    f'Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'
				with pytest.raises(__lowerCAmelCase					,     match=re.escape(__lowerCAmelCase				)				):
								metric.compute(predictions=[]					,     references=[]					,     scheme=__lowerCAmelCase				)





"""simple docstring"""


import argparse
from typing import Dict

import tensorflow as tf
import torch
from tqdm import tqdm

from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration


__A   :							Tuple										=   [
    # tf -> hf
    ("/", "."),
    ("layer_", "layers."),
    ("kernel", "weight"),
    ("beta", "bias"),
    ("gamma", "weight"),
    ("pegasus", "model"),
]
__A   :							int										=   [
    (".output.dense", ".fc2"),
    ("intermediate.LayerNorm", "final_layer_norm"),
    ("intermediate.dense", "fc1"),
]

__A   :							Tuple										=   (
    INIT_COMMON
    + [
        ("attention.self.LayerNorm", "self_attn_layer_norm"),
        ("attention.output.dense", "self_attn.out_proj"),
        ("attention.self", "self_attn"),
        ("attention.encdec.LayerNorm", "encoder_attn_layer_norm"),
        ("attention.encdec_output.dense", "encoder_attn.out_proj"),
        ("attention.encdec", "encoder_attn"),
        ("key", "k_proj"),
        ("value", "v_proj"),
        ("query", "q_proj"),
        ("decoder.LayerNorm", "decoder.layernorm_embedding"),
    ]
    + END_COMMON
)

__A   :							Optional[int]										=   (
    INIT_COMMON
    + [
        ("embeddings.word_embeddings", "shared.weight"),
        ("embeddings.position_embeddings", "embed_positions.weight"),
        ("attention.self.LayerNorm", "self_attn_layer_norm"),
        ("attention.output.dense", "self_attn.output"),
        ("attention.self", "self_attn.self"),
        ("encoder.LayerNorm", "encoder.layernorm_embedding"),
    ]
    + END_COMMON
)

__A   :							Union[str, Any]										=   [
    "encdec/key/bias",
    "encdec/query/bias",
    "encdec/value/bias",
    "self/key/bias",
    "self/query/bias",
    "self/value/bias",
    "encdec_output/dense/bias",
    "attention/output/dense/bias",
]







def  lowercase	(      _SCREAMING_SNAKE_CASE   :						Optional[int]					,     _SCREAMING_SNAKE_CASE   :						List[Any]				):






				'''simple docstring'''



				for tf_name, hf_name in patterns:
								_UpperCAmelCase					=    k.replace(_SCREAMING_SNAKE_CASE					,     _SCREAMING_SNAKE_CASE				)
				return k







def  lowercase	(      _SCREAMING_SNAKE_CASE   :						dict					,     _SCREAMING_SNAKE_CASE   :						dict				):






				'''simple docstring'''



				_UpperCAmelCase					=    BigBirdPegasusConfig(**_SCREAMING_SNAKE_CASE				)
				_UpperCAmelCase					=    BigBirdPegasusForConditionalGeneration(_SCREAMING_SNAKE_CASE				)
				_UpperCAmelCase					=    torch_model.state_dict()
				_UpperCAmelCase					=    {}

				# separating decoder weights
				_UpperCAmelCase					=    {k: tf_weights[k] for k in tf_weights if k.startswith('''pegasus/decoder'''				)}
				_UpperCAmelCase					=    {k: tf_weights[k] for k in tf_weights if not k.startswith('''pegasus/decoder'''				)}

				for k, v in tqdm(decoder_weights.items()					,     '''tf -> hf conversion'''				):
								_UpperCAmelCase					=    [k.endswith(_SCREAMING_SNAKE_CASE				) for ending in KEYS_TO_IGNORE]
								if any(_SCREAMING_SNAKE_CASE				):
												continue
								_UpperCAmelCase					=    DECODER_PATTERNS
								_UpperCAmelCase					=    rename_state_dict_key(_SCREAMING_SNAKE_CASE					,     _SCREAMING_SNAKE_CASE				)
								if new_k not in state_dict:
												raise ValueError(f'could not find new key {new_k} in state dict. (converted from {k})'				)
								if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value''']				):
												_UpperCAmelCase					=    v.T
								_UpperCAmelCase					=    torch.from_numpy(_SCREAMING_SNAKE_CASE				)
								assert v.shape == state_dict[new_k].shape, f'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}'

				for k, v in tqdm(remaining_weights.items()					,     '''tf -> hf conversion'''				):
								_UpperCAmelCase					=    [k.endswith(_SCREAMING_SNAKE_CASE				) for ending in KEYS_TO_IGNORE]
								if any(_SCREAMING_SNAKE_CASE				):
												continue
								_UpperCAmelCase					=    REMAINING_PATTERNS
								_UpperCAmelCase					=    rename_state_dict_key(_SCREAMING_SNAKE_CASE					,     _SCREAMING_SNAKE_CASE				)
								if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings":
												raise ValueError(f'could not find new key {new_k} in state dict. (converted from {k})'				)
								if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value''']				):
												_UpperCAmelCase					=    v.T
								_UpperCAmelCase					=    torch.from_numpy(_SCREAMING_SNAKE_CASE				)
								if k != "pegasus/embeddings/position_embeddings":
												assert v.shape == state_dict[new_k].shape, f'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}'

				_UpperCAmelCase					=    mapping['''model.embed_positions.weight''']
				_UpperCAmelCase					=    mapping.pop('''model.embed_positions.weight'''				)
				_UpperCAmelCase		,						_UpperCAmelCase					=    torch_model.load_state_dict(_SCREAMING_SNAKE_CASE					,     strict=_SCREAMING_SNAKE_CASE				)
				_UpperCAmelCase					=    [
				    k
				    for k in missing
				    if k
				    not in [
				        '''final_logits_bias''',
				        '''model.encoder.embed_tokens.weight''',
				        '''model.decoder.embed_tokens.weight''',
				        '''lm_head.weight''',
				    ]
				]
				assert unexpected_missing == [], f'no matches found for the following torch keys {unexpected_missing}'
				assert extra == [], f'no matches found for the following tf keys {extra}'
				return torch_model







def  lowercase	(      _SCREAMING_SNAKE_CASE   :						Any				):






				'''simple docstring'''



				_UpperCAmelCase					=    tf.train.list_variables(_SCREAMING_SNAKE_CASE				)
				_UpperCAmelCase					=    {}
				_UpperCAmelCase					=    ['''global_step''']
				for name, shape in tqdm(_SCREAMING_SNAKE_CASE					,     desc='''converting tf checkpoint to dict'''				):
								_UpperCAmelCase					=    any(pat in name for pat in ignore_name				)
								if skip_key:
												continue
								_UpperCAmelCase					=    tf.train.load_variable(_SCREAMING_SNAKE_CASE					,     _SCREAMING_SNAKE_CASE				)
								_UpperCAmelCase					=    array
				return tf_weights







def  lowercase	(      _SCREAMING_SNAKE_CASE   :						str					,     _SCREAMING_SNAKE_CASE   :						str					,     _SCREAMING_SNAKE_CASE   :						dict				):






				'''simple docstring'''



				_UpperCAmelCase					=    get_tf_weights_as_numpy(_SCREAMING_SNAKE_CASE				)
				_UpperCAmelCase					=    convert_bigbird_pegasus(_SCREAMING_SNAKE_CASE					,     _SCREAMING_SNAKE_CASE				)
				torch_model.save_pretrained(_SCREAMING_SNAKE_CASE				)


if __name__ == "__main__":
					__A   :							Tuple										=   argparse.ArgumentParser()
					parser.add_argument("--tf_ckpt_path", type=str, help="passed to tf.train.list_variables")
					parser.add_argument("--save_dir", default=None, type=str, help="Path to the output PyTorch model.")
					__A   :							Dict										=   parser.parse_args()
					__A   :							Tuple										=   {}
					convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)



