


"""simple docstring"""


import argparse

import pytorch_lightning as pl
import torch
from torch import nn

from transformers import LongformerForQuestionAnswering, LongformerModel
class   _UpperCamelCase  (   pl.LightningModule		):
							'''simple docstring'''







							def __init__(     self    ,   __a	):
										super().__init__()
										__lowerCAmelCase				    =			model
										__lowerCAmelCase				    =			2
										__lowerCAmelCase				    =			nn.Linear(self.model.config.hidden_size    ,   self.num_labels	)



							def 			snake_case				(     self	):
										pass


def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase      ):

			'''simple docstring'''




			__lowerCAmelCase				    =			LongformerModel.from_pretrained(_UpperCamelCase      )
			__lowerCAmelCase				    =			LightningModel(_UpperCamelCase      )

			__lowerCAmelCase				    =			torch.load(_UpperCamelCase    , map_location=torch.device("cpu"      )      )
			lightning_model.load_state_dict(ckpt["state_dict"]      )

			# init longformer question answering model
			__lowerCAmelCase				    =			LongformerForQuestionAnswering.from_pretrained(_UpperCamelCase      )

			# transfer weights
			longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict()      )
			longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict()      )
			longformer_for_qa.eval()

			# save model
			longformer_for_qa.save_pretrained(_UpperCamelCase      )

			print(f"Conversion successful. Model saved under {pytorch_dump_folder_path}"      )


if __name__ == "__main__":
	A     :   Tuple			    =			argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    "--longformer_model",
	    default=None,
	    type=str,
	    required=True,
	    help="model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.",
	)
	parser.add_argument(
	    "--longformer_question_answering_ckpt_path",
	    default=None,
	    type=str,
	    required=True,
	    help="Path the official PyTorch Lightning Checkpoint.",
	)
	parser.add_argument(
	    "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
	)
	A     :   Optional[int]			    =			parser.parse_args()
	convert_longformer_qa_checkpoint_to_pytorch(
	    args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path
	)








"""simple docstring"""


import unittest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TextaTextGenerationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch
from transformers.utils import is_torch_available

from .test_pipelines_common import ANY


if is_torch_available():
	import torch
@is_pipeline_test
class   _UpperCamelCase  (   unittest.TestCase		):
							'''simple docstring'''







							__UpperCAmelCase						:    Union[str, Any]				      =MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
							__UpperCAmelCase						:    Union[str, Any]				      =TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

							def 			snake_case				(     self    ,   __a    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			TextaTextGenerationPipeline(model=__a    ,   tokenizer=__a	)
										return generator, ["Something to write", "Something else"]

							def 			snake_case				(     self    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			generator("Something there"	)
										self.assertEqual(__a    ,   [{"generated_text": ANY(__a	)}]	)
										# These are encoder decoder, they don't just append to incoming string
										self.assertFalse(outputs[0]["generated_text"].startswith("Something there"	)	)

										__lowerCAmelCase				    =			generator(["This is great !", "Something else"]    ,   num_return_sequences=2    ,   do_sample=__a	)
										self.assertEqual(
										    __a    ,   [
										        [{"generated_text": ANY(__a	)}, {"generated_text": ANY(__a	)}],
										        [{"generated_text": ANY(__a	)}, {"generated_text": ANY(__a	)}],
										    ]    ,   )

										__lowerCAmelCase				    =			generator(
										    ["This is great !", "Something else"]    ,   num_return_sequences=2    ,   batch_size=2    ,   do_sample=__a	)
										self.assertEqual(
										    __a    ,   [
										        [{"generated_text": ANY(__a	)}, {"generated_text": ANY(__a	)}],
										        [{"generated_text": ANY(__a	)}, {"generated_text": ANY(__a	)}],
										    ]    ,   )

										with self.assertRaises(__a	):
													generator(4	)

							@require_torch
							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			pipeline("text2text-generation"    ,   model="patrickvonplaten/t5-tiny-random"    ,   framework="pt"	)
										# do_sample=False necessary for reproducibility
										__lowerCAmelCase				    =			generator("Something there"    ,   do_sample=__a	)
										self.assertEqual(__a    ,   [{"generated_text": ""}]	)

										__lowerCAmelCase				    =			3
										__lowerCAmelCase				    =			generator(
										    "Something there"    ,   num_return_sequences=__a    ,   num_beams=__a    ,   )
										__lowerCAmelCase				    =			[
										    {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide Beide"},
										    {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide"},
										    {"generated_text": ""},
										]
										self.assertEqual(__a    ,   __a	)

										__lowerCAmelCase				    =			generator("This is a test"    ,   do_sample=__a    ,   num_return_sequences=2    ,   return_tensors=__a	)
										self.assertEqual(
										    __a    ,   [
										        {"generated_token_ids": ANY(torch.Tensor	)},
										        {"generated_token_ids": ANY(torch.Tensor	)},
										    ]    ,   )
										__lowerCAmelCase				    =			generator.model.config.eos_token_id
										__lowerCAmelCase				    =			"<pad>"
										__lowerCAmelCase				    =			generator(
										    ["This is a test", "This is a second test"]    ,   do_sample=__a    ,   num_return_sequences=2    ,   batch_size=2    ,   return_tensors=__a    ,   )
										self.assertEqual(
										    __a    ,   [
										        [
										            {"generated_token_ids": ANY(torch.Tensor	)},
										            {"generated_token_ids": ANY(torch.Tensor	)},
										        ],
										        [
										            {"generated_token_ids": ANY(torch.Tensor	)},
										            {"generated_token_ids": ANY(torch.Tensor	)},
										        ],
										    ]    ,   )



							@require_tf
							def 			snake_case				(     self	):
										__lowerCAmelCase				    =			pipeline("text2text-generation"    ,   model="patrickvonplaten/t5-tiny-random"    ,   framework="tf"	)
										# do_sample=False necessary for reproducibility
										__lowerCAmelCase				    =			generator("Something there"    ,   do_sample=__a	)
										self.assertEqual(__a    ,   [{"generated_text": ""}]	)




