





from copy import deepcopy
from unittest.case import TestCase

import pytest

from datasets.arrow_dataset import Dataset
from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value
from datasets.info import DatasetInfo
from datasets.tasks import (
    AudioClassification,
    AutomaticSpeechRecognition,
    ImageClassification,
    LanguageModeling,
    QuestionAnsweringExtractive,
    Summarization,
    TextClassification,
    task_template_from_dict,
)
from datasets.utils.py_utils import asdict


__A       : List[Any]						    = {
    "id": "5733be284776f41900661182",
    "title": "University_of_Notre_Dame",
    "context": "Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \"Venite Ad Me Omnes\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.",
    "question": "To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?",
    "answers": {"text": ["Saint Bernadette Soubirous"], "answer_start": [515]},
}





@pytest.mark.parametrize(
    'task_cls'       ,    [
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]       ,    )
def 							__lowerCAmelCase(					_SCREAMING_SNAKE_CASE							)       ->   Any:




    """simple docstring"""




    _A    =       task_cls()
    _A    =       asdict(UpperCAmelCase_							)
    _A    =       task_template_from_dict(UpperCAmelCase_							)
    assert task == reloaded







class     lowerCamelCase:
     '''simple docstring'''


     def 					lowerCAmelCase__		(						self       ):
         _A    =       LanguageModeling(text_column='input_text'       )
         assert {"input_text": "text"} == task.column_mapping




     def 					lowerCAmelCase__		(						self       ):
         _A    =       Features({'text': Value('string'       )}       )
         _A    =       {'''text_column''': '''input_text'''}
         _A    =       LanguageModeling.from_dict(snake_case_       )
         assert "language-modeling" == task.task
         assert input_schema == task.input_schema







class     lowerCamelCase(	A_  ):
     '''simple docstring'''


     def 					lowerCAmelCase__		(						self       ):
         _A    =       sorted(['pos', 'neg']       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       TextClassification(text_column='input_text'							,    label_column='input_label'       )
         self.assertDictEqual({'input_text': 'text', 'input_label': 'labels'}							,    task.column_mapping       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       Features({'text': Value('string'       )}       )
         # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
         _A    =       Features({'labels': ClassLabel}       )
         _A    =       {'''text_column''': '''input_text''', '''label_column''': '''input_labels'''}
         _A    =       TextClassification.from_dict(snake_case_       )
         self.assertEqual('text-classification'							,    task.task       )
         self.assertEqual(snake_case_							,    task.input_schema       )
         self.assertEqual(snake_case_							,    task.label_schema       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       TextClassification(text_column='input_text'							,    label_column='input_label'       )
         self.assertEqual(task.label_schema['labels']							,    snake_case_       )
         _A    =       task.align_with_features(Features({'input_label': ClassLabel(names=self.labels       )}       )       )
         self.assertEqual(task.label_schema['labels']							,    ClassLabel(names=self.labels       )       )







class     lowerCamelCase(	A_  ):
     '''simple docstring'''


     def 					lowerCAmelCase__		(						self       ):
         _A    =       QuestionAnsweringExtractive(
             context_column='input_context'							,    question_column='input_question'							,    answers_column='input_answers'       )
         self.assertDictEqual(
             {'input_context': 'context', 'input_question': 'question', 'input_answers': 'answers'}							,    task.column_mapping       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       Features({'question': Value('string'       ), 'context': Value('string'       )}       )
         _A    =       Features(
             {
                 'answers': Sequence(
                     {
                         'text': Value('string'       ),
                         'answer_start': Value('int32'       ),
                     }       )
             }       )
         _A    =       {
             '''context_column''': '''input_input_context''',
             '''question_column''': '''input_question''',
             '''answers_column''': '''input_answers''',
         }
         _A    =       QuestionAnsweringExtractive.from_dict(snake_case_       )
         self.assertEqual('question-answering-extractive'							,    task.task       )
         self.assertEqual(snake_case_							,    task.input_schema       )
         self.assertEqual(snake_case_							,    task.label_schema       )







class     lowerCamelCase(	A_  ):
     '''simple docstring'''


     def 					lowerCAmelCase__		(						self       ):
         _A    =       Summarization(text_column='input_text'							,    summary_column='input_summary'       )
         self.assertDictEqual({'input_text': 'text', 'input_summary': 'summary'}							,    task.column_mapping       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       Features({'text': Value('string'       )}       )
         _A    =       Features({'summary': Value('string'       )}       )
         _A    =       {'''text_column''': '''input_text''', '''summary_column''': '''input_summary'''}
         _A    =       Summarization.from_dict(snake_case_       )
         self.assertEqual('summarization'							,    task.task       )
         self.assertEqual(snake_case_							,    task.input_schema       )
         self.assertEqual(snake_case_							,    task.label_schema       )







class     lowerCamelCase(	A_  ):
     '''simple docstring'''


     def 					lowerCAmelCase__		(						self       ):
         _A    =       AutomaticSpeechRecognition(audio_column='input_audio'							,    transcription_column='input_transcription'       )
         self.assertDictEqual({'input_audio': 'audio', 'input_transcription': 'transcription'}							,    task.column_mapping       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       Features({'audio': Audio()}       )
         _A    =       Features({'transcription': Value('string'       )}       )
         _A    =       {
             '''audio_column''': '''input_audio''',
             '''transcription_column''': '''input_transcription''',
         }
         _A    =       AutomaticSpeechRecognition.from_dict(snake_case_       )
         self.assertEqual('automatic-speech-recognition'							,    task.task       )
         self.assertEqual(snake_case_							,    task.input_schema       )
         self.assertEqual(snake_case_							,    task.label_schema       )







class     lowerCamelCase(	A_  ):
     '''simple docstring'''


     def 					lowerCAmelCase__		(						self       ):
         _A    =       sorted(['pos', 'neg']       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       AudioClassification(audio_column='input_audio'							,    label_column='input_label'       )
         self.assertDictEqual({'input_audio': 'audio', 'input_label': 'labels'}							,    task.column_mapping       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       Features({'audio': Audio()}       )
         _A    =       Features({'labels': ClassLabel}       )
         _A    =       {
             '''audio_column''': '''input_image''',
             '''label_column''': '''input_label''',
         }
         _A    =       AudioClassification.from_dict(snake_case_       )
         self.assertEqual('audio-classification'							,    task.task       )
         self.assertEqual(snake_case_							,    task.input_schema       )
         self.assertEqual(snake_case_							,    task.label_schema       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       AudioClassification(audio_column='input_audio'							,    label_column='input_label'       )
         self.assertEqual(task.label_schema['labels']							,    snake_case_       )
         _A    =       task.align_with_features(Features({'input_label': ClassLabel(names=self.labels       )}       )       )
         self.assertEqual(task.label_schema['labels']							,    ClassLabel(names=self.labels       )       )







class     lowerCamelCase(	A_  ):
     '''simple docstring'''


     def 					lowerCAmelCase__		(						self       ):
         _A    =       sorted(['pos', 'neg']       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       ImageClassification(image_column='input_image'							,    label_column='input_label'       )
         self.assertDictEqual({'input_image': 'image', 'input_label': 'labels'}							,    task.column_mapping       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       Features({'image': Image()}       )
         _A    =       Features({'labels': ClassLabel}       )
         _A    =       {
             '''image_column''': '''input_image''',
             '''label_column''': '''input_label''',
         }
         _A    =       ImageClassification.from_dict(snake_case_       )
         self.assertEqual('image-classification'							,    task.task       )
         self.assertEqual(snake_case_							,    task.input_schema       )
         self.assertEqual(snake_case_							,    task.label_schema       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       ImageClassification(image_column='input_image'							,    label_column='input_label'       )
         self.assertEqual(task.label_schema['labels']							,    snake_case_       )
         _A    =       task.align_with_features(Features({'input_label': ClassLabel(names=self.labels       )}       )       )
         self.assertEqual(task.label_schema['labels']							,    ClassLabel(names=self.labels       )       )







class     lowerCamelCase(	A_  ):
     '''simple docstring'''


     def 					lowerCAmelCase__		(						self       ):
         _A    =       DatasetInfo(task_templates=QuestionAnsweringExtractive()       )
         _A    =       Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}							,    info=snake_case_       )
         assert isinstance(dataset.info.task_templates							,    snake_case_       )
         assert len(dataset.info.task_templates       ) == 1

         def keep_task(snake_case_       ):
             return x

         def dont_keep_task(snake_case_       ):
             _A    =       deepcopy(snake_case_       )
             _A    =       0
             return out

         _A    =       dataset.map(snake_case_       )
         assert mapped_dataset.info.task_templates == dataset.info.task_templates
         # reload from cache
         _A    =       dataset.map(snake_case_       )
         assert mapped_dataset.info.task_templates == dataset.info.task_templates

         _A    =       dataset.map(snake_case_       )
         assert mapped_dataset.info.task_templates == []
         # reload from cache
         _A    =       dataset.map(snake_case_       )
         assert mapped_dataset.info.task_templates == []




     def 					lowerCAmelCase__		(						self       ):
         _A    =       Features({'text': Value('string'       ), 'label': ClassLabel(names=('pos', 'neg')       )}       )
         _A    =       TextClassification(text_column='text'							,    label_column='label'       )
         _A    =       DatasetInfo(features=snake_case_							,    task_templates=snake_case_       )
         _A    =       Dataset.from_dict({'text': ['A sentence.'], 'label': ['pos']}							,    info=snake_case_       )

         def process(snake_case_       ):
             return example

         _A    =       dataset.remove_columns('label'       )
         _A    =       modified_dataset.map(snake_case_       )
         assert mapped_dataset.info.task_templates == []












import argparse

import torch
from flax.training.checkpoints import restore_checkpoint

from transformers import FNetConfig, FNetForPreTraining
from transformers.utils import logging


logging.set_verbosity_info()





def 							__lowerCAmelCase(					_SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE							)       ->   List[str]:




    """simple docstring"""




    _A    =       FNetConfig.from_json_file(_SCREAMING_SNAKE_CASE							)
    print(F"Building PyTorch model from configuration: {config}"							)
    _A    =       FNetForPreTraining(_SCREAMING_SNAKE_CASE							)

    _A    =       restore_checkpoint(_SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE							)
    _A    =       checkpoint_dict['target']

    # Embeddings
    # Position IDs
    _A    =       fnet_pretraining_model.state_dict()

    _A    =       state_dict['fnet.embeddings.position_ids']
    _A    =       {'fnet.embeddings.position_ids': position_ids}
    # Embedding Layers
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['word']['embedding']							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['position']['embedding'][0]							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['type']['embedding']							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['hidden_mapping_in']['kernel']							).T
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['hidden_mapping_in']['bias']							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['layer_norm']['scale']							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['layer_norm']['bias']							)

    # Encoder Layers
    for layer in range(config.num_hidden_layers							):
        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"encoder_{layer}"]['mixing_layer_norm']['scale']							)
        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"encoder_{layer}"]['mixing_layer_norm']['bias']							)

        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"feed_forward_{layer}"]['intermediate']['kernel']							).T
        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"feed_forward_{layer}"]['intermediate']['bias']							)

        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"feed_forward_{layer}"]['output']['kernel']							).T
        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"feed_forward_{layer}"]['output']['bias']							)

        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"encoder_{layer}"]['output_layer_norm']['scale']							)
        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"encoder_{layer}"]['output_layer_norm']['bias']							)

    # Pooler Layers
    _A    =       torch.tensor(pretrained_model_params['encoder']['pooler']['kernel']							).T
    _A    =       torch.tensor(pretrained_model_params['encoder']['pooler']['bias']							)

    # Masked LM Layers
    _A    =       torch.tensor(
        pretrained_model_params['predictions_dense']['kernel']							).T
    _A    =       torch.tensor(
        pretrained_model_params['predictions_dense']['bias']							)
    _A    =       torch.tensor(
        pretrained_model_params['predictions_layer_norm']['scale']							)
    _A    =       torch.tensor(
        pretrained_model_params['predictions_layer_norm']['bias']							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['word']['embedding']							)
    _A    =       torch.tensor(
        pretrained_model_params['predictions_output']['output_bias']							)
    _A    =       torch.tensor(pretrained_model_params['predictions_output']['output_bias']							)

    # Seq Relationship Layers
    _A    =       torch.tensor(
        pretrained_model_params['classification']['output_kernel']							)
    _A    =       torch.tensor(
        pretrained_model_params['classification']['output_bias']							)

    # Load State Dict
    fnet_pretraining_model.load_state_dict(_SCREAMING_SNAKE_CASE							)

    # Save PreTrained
    print(F"Saving pretrained model to {save_path}"							)
    fnet_pretraining_model.save_pretrained(_SCREAMING_SNAKE_CASE							)


if __name__ == "__main__":
 __A       : str						    = argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     "--flax_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
 )
 parser.add_argument(
     "--fnet_config_file",
     default=None,
     type=str,
     required=True,
     help=(
         "The config json file corresponding to the pre-trained FNet model. \n"
         "This specifies the model architecture."
     ),
 )
 parser.add_argument("--save_path", default=None, type=str, required=True, help="Path to the output model.")
 __A       : Any						    = parser.parse_args()
 convert_flax_checkpoint_to_pytorch(args.flax_checkpoint_path, args.fnet_config_file, args.save_path)





