




'''simple docstring'''
import argparse
import os

import torch
from torchvision.datasets.utils import download_url

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, TransformeraDModel


A							:				str			     =	{512: """DiT-XL-2-512x512.pt""", 256: """DiT-XL-2-256x256.pt"""}
def     snake_case_  (       a__		:     Tuple      ):



    """simple docstring"""




    __lowercase      =						f'pretrained_models/{model_name}'
    if not os.path.isfile(a__      ):
        os.makedirs("""pretrained_models"""   ,exist_ok=a__      )
        __lowercase      =						f'https://dl.fbaipublicfiles.com/DiT/models/{model_name}'
        download_url(a__   ,"""pretrained_models"""      )
    __lowercase      =						torch.load(a__   ,map_location=lambda a__   ,a__      : storage      )
    return model
def     snake_case_  (       a__		:     Optional[Any]      ):



    """simple docstring"""




    __lowercase      =						download_model(pretrained_models[args.image_size]      )

    __lowercase      =						state_dict["""x_embedder.proj.weight"""]
    __lowercase      =						state_dict["""x_embedder.proj.bias"""]
    state_dict.pop("""x_embedder.proj.weight"""      )
    state_dict.pop("""x_embedder.proj.bias"""      )

    for depth in range(28      ):
        __lowercase      =						state_dict[
            """t_embedder.mlp.0.weight"""
        ]
        __lowercase      =						state_dict[
            """t_embedder.mlp.0.bias"""
        ]
        __lowercase      =						state_dict[
            """t_embedder.mlp.2.weight"""
        ]
        __lowercase      =						state_dict[
            """t_embedder.mlp.2.bias"""
        ]
        __lowercase      =						state_dict[
            """y_embedder.embedding_table.weight"""
        ]

        __lowercase      =						state_dict[
            f'blocks.{depth}.adaLN_modulation.1.weight'
        ]
        __lowercase      =						state_dict[
            f'blocks.{depth}.adaLN_modulation.1.bias'
        ]

        __lowercase,__lowercase,__lowercase      =						torch.chunk(state_dict[f'blocks.{depth}.attn.qkv.weight']   ,3   ,dim=0      )
        __lowercase,__lowercase,__lowercase      =						torch.chunk(state_dict[f'blocks.{depth}.attn.qkv.bias']   ,3   ,dim=0      )

        __lowercase      =						q
        __lowercase      =						q_bias
        __lowercase      =						k
        __lowercase      =						k_bias
        __lowercase      =						v
        __lowercase      =						v_bias

        __lowercase      =						state_dict[
            f'blocks.{depth}.attn.proj.weight'
        ]
        __lowercase      =						state_dict[f'blocks.{depth}.attn.proj.bias']

        __lowercase      =						state_dict[f'blocks.{depth}.mlp.fc1.weight']
        __lowercase      =						state_dict[f'blocks.{depth}.mlp.fc1.bias']
        __lowercase      =						state_dict[f'blocks.{depth}.mlp.fc2.weight']
        __lowercase      =						state_dict[f'blocks.{depth}.mlp.fc2.bias']

        state_dict.pop(f'blocks.{depth}.attn.qkv.weight'      )
        state_dict.pop(f'blocks.{depth}.attn.qkv.bias'      )
        state_dict.pop(f'blocks.{depth}.attn.proj.weight'      )
        state_dict.pop(f'blocks.{depth}.attn.proj.bias'      )
        state_dict.pop(f'blocks.{depth}.mlp.fc1.weight'      )
        state_dict.pop(f'blocks.{depth}.mlp.fc1.bias'      )
        state_dict.pop(f'blocks.{depth}.mlp.fc2.weight'      )
        state_dict.pop(f'blocks.{depth}.mlp.fc2.bias'      )
        state_dict.pop(f'blocks.{depth}.adaLN_modulation.1.weight'      )
        state_dict.pop(f'blocks.{depth}.adaLN_modulation.1.bias'      )

    state_dict.pop("""t_embedder.mlp.0.weight"""      )
    state_dict.pop("""t_embedder.mlp.0.bias"""      )
    state_dict.pop("""t_embedder.mlp.2.weight"""      )
    state_dict.pop("""t_embedder.mlp.2.bias"""      )
    state_dict.pop("""y_embedder.embedding_table.weight"""      )

    __lowercase      =						state_dict["""final_layer.adaLN_modulation.1.weight"""]
    __lowercase      =						state_dict["""final_layer.adaLN_modulation.1.bias"""]
    __lowercase      =						state_dict["""final_layer.linear.weight"""]
    __lowercase      =						state_dict["""final_layer.linear.bias"""]

    state_dict.pop("""final_layer.linear.weight"""      )
    state_dict.pop("""final_layer.linear.bias"""      )
    state_dict.pop("""final_layer.adaLN_modulation.1.weight"""      )
    state_dict.pop("""final_layer.adaLN_modulation.1.bias"""      )

    # DiT XL/2
    __lowercase      =						TransformeraDModel(
        sample_size=args.image_size // 8   ,num_layers=28   ,attention_head_dim=72   ,in_channels=4   ,out_channels=8   ,patch_size=2   ,attention_bias=a__   ,num_attention_heads=16   ,activation_fn="""gelu-approximate"""   ,num_embeds_ada_norm=10_00   ,norm_type="""ada_norm_zero"""   ,norm_elementwise_affine=a__   ,)
    transformer.load_state_dict(a__   ,strict=a__      )

    __lowercase      =						DDIMScheduler(
        num_train_timesteps=10_00   ,beta_schedule="""linear"""   ,prediction_type="""epsilon"""   ,clip_sample=a__   ,)

    __lowercase      =						AutoencoderKL.from_pretrained(args.vae_model      )

    __lowercase      =						DiTPipeline(transformer=a__   ,vae=a__   ,scheduler=a__      )

    if args.save:
        pipeline.save_pretrained(args.checkpoint_path      )


if __name__ == "__main__":
  A							:				List[str]			     =	argparse.ArgumentParser()

  parser.add_argument(
      """--image_size""",
      default=256,
      type=int,
      required=False,
      help="""Image size of pretrained model, either 256 or 512.""",
  )
  parser.add_argument(
      """--vae_model""",
      default="""stabilityai/sd-vae-ft-ema""",
      type=str,
      required=False,
      help="""Path to pretrained VAE model, either stabilityai/sd-vae-ft-mse or stabilityai/sd-vae-ft-ema.""",
  )
  parser.add_argument(
      """--save""", default=True, type=bool, required=False, help="""Whether to save the converted pipeline or not."""
  )
  parser.add_argument(
      """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output pipeline."""
  )

  A							:				Dict			     =	parser.parse_args()
  main(args)










'''simple docstring'''
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							:				Dict			     =	{
    """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     snake_case_  (       a__		:     str      ):



    """simple docstring"""




    __lowercase          =						task_cls()
    __lowercase          =						asdict(a__      )
    __lowercase          =						task_template_from_dict(a__      )
    assert task == reloaded






class 	SCREAMING_SNAKE_CASE:

       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						LanguageModeling(text_column="""input_text"""					)
           assert {"input_text": "text"} == task.column_mapping




       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           __lowercase          =						{"""text_column""": """input_text"""}
           __lowercase          =						LanguageModeling.from_dict(lowerCamelCase__					)
           assert "language-modeling" == task.task
           assert input_schema == task.input_schema






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						TextClassification(text_column="""input_text""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_text""": """text""", """input_label""": """labels"""} ,		task.column_mapping					)

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



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




       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						TextClassification(text_column="""input_text""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						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    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



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






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> int:

           """simple docstring"""



           __lowercase          =						Summarization(text_column="""input_text""" ,		summary_column="""input_summary"""					)
           self.assertDictEqual({"""input_text""": """text""", """input_summary""": """summary"""} ,		task.column_mapping					)




       def    snake_case__      (   self					)   -> Union[str, Any]:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					)}					)
           __lowercase          =						Features({"""summary""": Value("""string"""					)}					)
           __lowercase          =						{"""text_column""": """input_text""", """summary_column""": """input_summary"""}
           __lowercase          =						Summarization.from_dict(lowerCamelCase__					)
           self.assertEqual("""summarization""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						AutomaticSpeechRecognition(audio_column="""input_audio""" ,		transcription_column="""input_transcription"""					)
           self.assertDictEqual({"""input_audio""": """audio""", """input_transcription""": """transcription"""} ,		task.column_mapping					)




       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						Features({"""audio""": Audio()}					)
           __lowercase          =						Features({"""transcription""": Value("""string"""					)}					)
           __lowercase          =						{
               """audio_column""": """input_audio""",
               """transcription_column""": """input_transcription""",
           }
           __lowercase          =						AutomaticSpeechRecognition.from_dict(lowerCamelCase__					)
           self.assertEqual("""automatic-speech-recognition""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> List[Any]:

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

       def    snake_case__      (   self					)   -> Optional[Any]:

           """simple docstring"""



           __lowercase          =						AudioClassification(audio_column="""input_audio""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_audio""": """audio""", """input_label""": """labels"""} ,		task.column_mapping					)

       def    snake_case__      (   self					)   -> Optional[Any]:

           """simple docstring"""



           __lowercase          =						Features({"""audio""": Audio()}					)
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{
               """audio_column""": """input_image""",
               """label_column""": """input_label""",
           }
           __lowercase          =						AudioClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""audio-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						AudioClassification(audio_column="""input_audio""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Optional[Any]:

           """simple docstring"""



           __lowercase          =						sorted(["""pos""", """neg"""]					)

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						ImageClassification(image_column="""input_image""" ,		label_column="""input_label"""					)
           self.assertDictEqual({"""input_image""": """image""", """input_label""": """labels"""} ,		task.column_mapping					)

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						Features({"""image""": Image()}					)
           __lowercase          =						Features({"""labels""": ClassLabel}					)
           __lowercase          =						{
               """image_column""": """input_image""",
               """label_column""": """input_label""",
           }
           __lowercase          =						ImageClassification.from_dict(lowerCamelCase__					)
           self.assertEqual("""image-classification""" ,		task.task					)
           self.assertEqual(lowerCamelCase__ ,		task.input_schema					)
           self.assertEqual(lowerCamelCase__ ,		task.label_schema					)




       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						ImageClassification(image_column="""input_image""" ,		label_column="""input_label"""					)
           self.assertEqual(task.label_schema["""labels"""] ,		lowerCamelCase__					)
           __lowercase          =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels					)}					)					)
           self.assertEqual(task.label_schema["""labels"""] ,		ClassLabel(names=self.labels					)					)






class 	SCREAMING_SNAKE_CASE(    __A					):

       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						DatasetInfo(task_templates=QuestionAnsweringExtractive()					)
           __lowercase          =						Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()} ,		info=lowerCamelCase__					)
           assert isinstance(dataset.info.task_templates ,		lowerCamelCase__					)
           assert len(dataset.info.task_templates					) == 1

           def keep_task(lowerCamelCase__					):
               return x

           def dont_keep_task(lowerCamelCase__					):
               __lowercase          =						deepcopy(lowerCamelCase__					)
               __lowercase          =						0
               return out

           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == dataset.info.task_templates
           # reload from cache
           __lowercase          =						dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == dataset.info.task_templates

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




       def    snake_case__      (   self					)   -> Union[str, Any]:

           """simple docstring"""



           __lowercase          =						Features({"""text""": Value("""string"""					), """label""": ClassLabel(names=("""pos""", """neg""")					)}					)
           __lowercase          =						TextClassification(text_column="""text""" ,		label_column="""label"""					)
           __lowercase          =						DatasetInfo(features=lowerCamelCase__ ,		task_templates=lowerCamelCase__					)
           __lowercase          =						Dataset.from_dict({"""text""": ["""A sentence."""], """label""": ["""pos"""]} ,		info=lowerCamelCase__					)

           def process(lowerCamelCase__					):
               return example

           __lowercase          =						dataset.remove_columns("""label"""					)
           __lowercase          =						modified_dataset.map(lowerCamelCase__					)
           assert mapped_dataset.info.task_templates == []




