code: 
  
  
  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
  
  
  UpperCamelCase__				       =			{
      '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   UpperCamelCase__   (    UpperCAmelCase_			)						->							Any:
  
  
  
  
         '''simple docstring'''
  
  
  
  
  
  
         _lowercase					:				str           =			task_cls()
         _lowercase					:				Optional[Any]           =			asdict(UpperCAmelCase_			)
         _lowercase					:				Any           =			task_template_from_dict(UpperCAmelCase_			)
         assert task == reloaded
  
  class 						UpperCAmelCase__   :
  
  
  
       '''simple docstring'''
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Dict		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Any           =			LanguageModeling(text_column='''input_text'''		)
              assert {"input_text": "text"} == task.column_mapping
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Tuple		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Optional[Any]           =			Features({'''text''': Value('''string'''		)}		)
              _lowercase					:				Any           =			{'''text_column''': '''input_text'''}
              _lowercase					:				Any           =			LanguageModeling.from_dict(UpperCamelCase		)
              assert "language-modeling" == task.task
              assert input_schema == task.input_schema
  
  
  
  
  class 						UpperCAmelCase__   (      A_		):
  
  
  
       '''simple docstring'''
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Optional[Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Any           =			sorted(['''pos''', '''neg''']		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       List[Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Any           =			TextClassification(text_column='''input_text'''	,      label_column='''input_label'''		)
              self.assertDictEqual({'''input_text''': '''text''', '''input_label''': '''labels'''}	,      task.column_mapping		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Union[str, Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Tuple           =			Features({'''text''': Value('''string'''		)}		)
              # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
              _lowercase					:				Dict           =			Features({'''labels''': ClassLabel}		)
              _lowercase					:				Any           =			{'''text_column''': '''input_text''', '''label_column''': '''input_labels'''}
              _lowercase					:				Dict           =			TextClassification.from_dict(UpperCamelCase		)
              self.assertEqual('''text-classification'''	,      task.task		)
              self.assertEqual(UpperCamelCase	,      task.input_schema		)
              self.assertEqual(UpperCamelCase	,      task.label_schema		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       List[Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Union[str, Any]           =			TextClassification(text_column='''input_text'''	,      label_column='''input_label'''		)
              self.assertEqual(task.label_schema['''labels''']	,      UpperCamelCase		)
              _lowercase					:				Any           =			task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels		)}		)		)
              self.assertEqual(task.label_schema['''labels''']	,      ClassLabel(names=self.labels		)		)
  
  
  
  
  class 						UpperCAmelCase__   (      A_		):
  
  
  
       '''simple docstring'''
  
  
  
  
       def   lowerCAmelCase_   ( self       :       str		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				str           =			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       :       Dict		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Optional[int]           =			Features({'''question''': Value('''string'''		), '''context''': Value('''string'''		)}		)
              _lowercase					:				Optional[int]           =			Features(
                  {
                      '''answers''': Sequence(
                          {
                              '''text''': Value('''string'''		),
                              '''answer_start''': Value('''int32'''		),
                          }		)
                  }		)
              _lowercase					:				Tuple           =			{
                  '''context_column''': '''input_input_context''',
                  '''question_column''': '''input_question''',
                  '''answers_column''': '''input_answers''',
              }
              _lowercase					:				int           =			QuestionAnsweringExtractive.from_dict(UpperCamelCase		)
              self.assertEqual('''question-answering-extractive'''	,      task.task		)
              self.assertEqual(UpperCamelCase	,      task.input_schema		)
              self.assertEqual(UpperCamelCase	,      task.label_schema		)
  
  
  
  
  class 						UpperCAmelCase__   (      A_		):
  
  
  
       '''simple docstring'''
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Optional[Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Dict           =			Summarization(text_column='''input_text'''	,      summary_column='''input_summary'''		)
              self.assertDictEqual({'''input_text''': '''text''', '''input_summary''': '''summary'''}	,      task.column_mapping		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Tuple		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Optional[Any]           =			Features({'''text''': Value('''string'''		)}		)
              _lowercase					:				Optional[Any]           =			Features({'''summary''': Value('''string'''		)}		)
              _lowercase					:				Optional[int]           =			{'''text_column''': '''input_text''', '''summary_column''': '''input_summary'''}
              _lowercase					:				str           =			Summarization.from_dict(UpperCamelCase		)
              self.assertEqual('''summarization'''	,      task.task		)
              self.assertEqual(UpperCamelCase	,      task.input_schema		)
              self.assertEqual(UpperCamelCase	,      task.label_schema		)
  
  
  
  
  class 						UpperCAmelCase__   (      A_		):
  
  
  
       '''simple docstring'''
  
  
  
  
       def   lowerCAmelCase_   ( self       :       List[str]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				List[Any]           =			AutomaticSpeechRecognition(audio_column='''input_audio'''	,      transcription_column='''input_transcription'''		)
              self.assertDictEqual({'''input_audio''': '''audio''', '''input_transcription''': '''transcription'''}	,      task.column_mapping		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Dict		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				List[str]           =			Features({'''audio''': Audio()}		)
              _lowercase					:				List[Any]           =			Features({'''transcription''': Value('''string'''		)}		)
              _lowercase					:				Optional[Any]           =			{
                  '''audio_column''': '''input_audio''',
                  '''transcription_column''': '''input_transcription''',
              }
              _lowercase					:				Union[str, Any]           =			AutomaticSpeechRecognition.from_dict(UpperCamelCase		)
              self.assertEqual('''automatic-speech-recognition'''	,      task.task		)
              self.assertEqual(UpperCamelCase	,      task.input_schema		)
              self.assertEqual(UpperCamelCase	,      task.label_schema		)
  
  
  
  
  class 						UpperCAmelCase__   (      A_		):
  
  
  
       '''simple docstring'''
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Tuple		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Any           =			sorted(['''pos''', '''neg''']		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       List[Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Dict           =			AudioClassification(audio_column='''input_audio'''	,      label_column='''input_label'''		)
              self.assertDictEqual({'''input_audio''': '''audio''', '''input_label''': '''labels'''}	,      task.column_mapping		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Optional[Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Optional[int]           =			Features({'''audio''': Audio()}		)
              _lowercase					:				Optional[int]           =			Features({'''labels''': ClassLabel}		)
              _lowercase					:				Union[str, Any]           =			{
                  '''audio_column''': '''input_image''',
                  '''label_column''': '''input_label''',
              }
              _lowercase					:				Optional[int]           =			AudioClassification.from_dict(UpperCamelCase		)
              self.assertEqual('''audio-classification'''	,      task.task		)
              self.assertEqual(UpperCamelCase	,      task.input_schema		)
              self.assertEqual(UpperCamelCase	,      task.label_schema		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       str		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				str           =			AudioClassification(audio_column='''input_audio'''	,      label_column='''input_label'''		)
              self.assertEqual(task.label_schema['''labels''']	,      UpperCamelCase		)
              _lowercase					:				Optional[Any]           =			task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels		)}		)		)
              self.assertEqual(task.label_schema['''labels''']	,      ClassLabel(names=self.labels		)		)
  
  
  
  
  class 						UpperCAmelCase__   (      A_		):
  
  
  
       '''simple docstring'''
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Union[str, Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				List[Any]           =			sorted(['''pos''', '''neg''']		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Optional[Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				List[str]           =			ImageClassification(image_column='''input_image'''	,      label_column='''input_label'''		)
              self.assertDictEqual({'''input_image''': '''image''', '''input_label''': '''labels'''}	,      task.column_mapping		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Union[str, Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				int           =			Features({'''image''': Image()}		)
              _lowercase					:				Optional[int]           =			Features({'''labels''': ClassLabel}		)
              _lowercase					:				int           =			{
                  '''image_column''': '''input_image''',
                  '''label_column''': '''input_label''',
              }
              _lowercase					:				Tuple           =			ImageClassification.from_dict(UpperCamelCase		)
              self.assertEqual('''image-classification'''	,      task.task		)
              self.assertEqual(UpperCamelCase	,      task.input_schema		)
              self.assertEqual(UpperCamelCase	,      task.label_schema		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       List[Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				int           =			ImageClassification(image_column='''input_image'''	,      label_column='''input_label'''		)
              self.assertEqual(task.label_schema['''labels''']	,      UpperCamelCase		)
              _lowercase					:				List[Any]           =			task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels		)}		)		)
              self.assertEqual(task.label_schema['''labels''']	,      ClassLabel(names=self.labels		)		)
  
  
  
  
  class 						UpperCAmelCase__   (      A_		):
  
  
  
       '''simple docstring'''
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Tuple		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				List[Any]           =			DatasetInfo(task_templates=QuestionAnsweringExtractive()		)
              _lowercase					:				Dict           =			Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}	,      info=UpperCamelCase		)
              assert isinstance(dataset.info.task_templates	,      UpperCamelCase		)
              assert len(dataset.info.task_templates		) == 1
  
              def keep_task(UpperCamelCase       :       List[str]		):
                     return x
  
              def dont_keep_task(UpperCamelCase       :       Optional[int]		):
                     _lowercase					:				Union[str, Any]           =			deepcopy(UpperCamelCase		)
                     _lowercase					:				Dict           =			0
                     return out
  
              _lowercase					:				Optional[int]           =			dataset.map(UpperCamelCase		)
              assert mapped_dataset.info.task_templates == dataset.info.task_templates
              # reload from cache
              _lowercase					:				List[str]           =			dataset.map(UpperCamelCase		)
              assert mapped_dataset.info.task_templates == dataset.info.task_templates
  
              _lowercase					:				str           =			dataset.map(UpperCamelCase		)
              assert mapped_dataset.info.task_templates == []
              # reload from cache
              _lowercase					:				Any           =			dataset.map(UpperCamelCase		)
              assert mapped_dataset.info.task_templates == []
  
  
  
  
       def   lowerCAmelCase_   ( self       :       str		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Optional[int]           =			Features({'''text''': Value('''string'''		), '''label''': ClassLabel(names=('''pos''', '''neg''')		)}		)
              _lowercase					:				Union[str, Any]           =			TextClassification(text_column='''text'''	,      label_column='''label'''		)
              _lowercase					:				List[Any]           =			DatasetInfo(features=UpperCamelCase	,      task_templates=UpperCamelCase		)
              _lowercase					:				Optional[int]           =			Dataset.from_dict({'''text''': ['''A sentence.'''], '''label''': ['''pos''']}	,      info=UpperCamelCase		)
  
              def process(UpperCamelCase       :       str		):
                     return example
  
              _lowercase					:				Tuple           =			dataset.remove_columns('''label'''		)
              _lowercase					:				Any           =			modified_dataset.map(UpperCamelCase		)
              assert mapped_dataset.info.task_templates == []
style_context: 
  
  
  import os
  from pathlib import Path
  from typing import Dict, List
  
  import fire
  import torch
  
  from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
  from transformers.utils.logging import get_logger
  
  
  UpperCamelCase__				       =			get_logger(__name__)
  
  def   UpperCamelCase__   (    UpperCAmelCase_    ,     UpperCAmelCase_			)						->							List[str]:
  
  
  
  
         '''simple docstring'''
  
  
  
  
  
  
         if text.startswith(UpperCAmelCase_			):
                return text[len(UpperCAmelCase_			) :]
         return text  # or whatever
  
  def   UpperCamelCase__   (    UpperCAmelCase_			)						->							Optional[int]:
  
  
  
  
         '''simple docstring'''
  
  
  
  
  
  
         return {remove_prefix(UpperCAmelCase_    ,     '''model.'''			): v for k, v in sd.items()}
  
  def   UpperCamelCase__   (    UpperCAmelCase_			)						->							Any:
  
  
  
  
         '''simple docstring'''
  
  
  
  
  
  
         _lowercase					:				Optional[int]           =			{}
         for k in state_dicts[0].keys():
                _lowercase					:				Tuple           =			[sd[k] for sd in state_dicts]
                _lowercase					:				Union[str, Any]           =			sum(UpperCAmelCase_			) / len(UpperCAmelCase_			)
                assert isinstance(UpperCAmelCase_    ,     torch.Tensor			)
                _lowercase					:				Union[str, Any]           =			new_t
         return new_sd
  
  def   UpperCamelCase__   (    UpperCAmelCase_    ,     UpperCAmelCase_    ,     UpperCAmelCase_			)						->							None:
  
  
  
  
         '''simple docstring'''
  
  
  
  
  
  
         _lowercase					:				List[str]           =			AutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase_			)
         if os.path.isfile(UpperCAmelCase_			):
                _lowercase					:				Optional[Any]           =			[pl_ckpt_path]
         else:
                assert os.path.isdir(UpperCAmelCase_			)
                _lowercase					:				List[str]           =			list(Path(UpperCAmelCase_			).glob('''*.ckpt'''			)			)
                assert ckpt_files, F'could not find any ckpt files inside the {pl_ckpt_path} directory'
  
         if len(UpperCAmelCase_			) > 1:
                logger.info(F'averaging the weights of {ckpt_files}'			)
  
         _lowercase					:				List[Any]           =			[sanitize(torch.load(UpperCAmelCase_    ,     map_location='''cpu'''			)['''state_dict''']			) for x in ckpt_files]
         _lowercase					:				Optional[Any]           =			average_state_dicts(UpperCAmelCase_			)
  
         _lowercase       ,	_lowercase					:				str           =			hf_model.load_state_dict(UpperCAmelCase_    ,     strict=UpperCAmelCase_			)
         assert not missing, F'missing keys: {missing}'
         hf_model.save_pretrained(UpperCAmelCase_			)
         try:
                _lowercase					:				Union[str, Any]           =			AutoTokenizer.from_pretrained(UpperCAmelCase_			)
                tok.save_pretrained(UpperCAmelCase_			)
         except Exception:
                pass
                # dont copy tokenizer if cant
  
  
  if __name__ == "__main__":
     fire.Fire(convert_pl_to_hf)