





import argparse
import json

import numpy
import torch

from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()



def A_	(		A__		,      A__				)  ->		List[str]:
       a__						:	Optional[Any] =				torch.load(SCREAMING_SNAKE_CASE_		,      map_location='cpu'				)

       a__						:	Any =				chkpt["model"]

       # We have the base model one level deeper than the original XLM repository
       a__						:	Dict =				{}
       for k, v in state_dict.items():
              if "pred_layer" in k:
                     a__						:	Optional[int] =				v
              else:
                     a__						:	int =				v

       a__						:	Union[str, Any] =				chkpt["params"]
       a__						:	int =				{n: v for n, v in config.items() if not isinstance(SCREAMING_SNAKE_CASE_		,      (torch.FloatTensor, numpy.ndarray)				)}

       a__						:	int =				chkpt["dico_word2id"]
       a__						:	Any =				{s + "</w>" if s.find('@@'				) == -1 and i > 13 else s.replace('@@'		,      ''				): i for s, i in vocab.items()}

       # Save pytorch-model
       a__						:	List[str] =				pytorch_dump_folder_path + "/" + WEIGHTS_NAME
       a__						:	Optional[int] =				pytorch_dump_folder_path + "/" + CONFIG_NAME
       a__						:	Optional[int] =				pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"]

       print(F'Save PyTorch model to {pytorch_weights_dump_path}'				)
       torch.save(SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_				)

       print(F'Save configuration file to {pytorch_config_dump_path}'				)
       with open(SCREAMING_SNAKE_CASE_		,      'w'		,      encoding='utf-8'				) as f:
              f.write(json.dumps(SCREAMING_SNAKE_CASE_		,      indent=2				) + '\n'				)

       print(F'Save vocab file to {pytorch_config_dump_path}'				)
       with open(SCREAMING_SNAKE_CASE_		,      'w'		,      encoding='utf-8'				) as f:
              f.write(json.dumps(SCREAMING_SNAKE_CASE_		,      indent=2				) + '\n'				)


if __name__ == "__main__":
    lowercase      :       List[Any]									=  argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        """--xlm_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump."""
    )
    parser.add_argument(
        """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
    )
    lowercase      :       str									=  parser.parse_args()
    convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)






import argparse

import intel_extension_for_pytorch as ipex
import torch

from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline


_snake_case             =     argparse.ArgumentParser('''Stable Diffusion script with intel optimization''', add_help=False)
parser.add_argument('''--dpm''', action='''store_true''', help='''Enable DPMSolver or not''')
parser.add_argument('''--steps''', default=None, type=int, help='''Num inference steps''')
_snake_case             =     parser.parse_args()


_snake_case             =     '''cpu'''
_snake_case             =     '''a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings'''

_snake_case             =     '''path-to-your-trained-model'''
_snake_case             =     StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
   _snake_case             =     DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
_snake_case             =     pipe.to(device)

# to channels last
_snake_case             =     pipe.unet.to(memory_format=torch.channels_last)
_snake_case             =     pipe.vae.to(memory_format=torch.channels_last)
_snake_case             =     pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
   _snake_case             =     pipe.safety_checker.to(memory_format=torch.channels_last)

# optimize with ipex
_snake_case             =     torch.randn(2, 4, 64, 64)
_snake_case             =     torch.rand(1) * 9_99
_snake_case             =     torch.randn(2, 77, 7_68)
_snake_case             =     (sample, timestep, encoder_hidden_status)
try:
   _snake_case             =     ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example)
except Exception:
   _snake_case             =     ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True)
_snake_case             =     ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True)
_snake_case             =     ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True)
if pipe.requires_safety_checker:
   _snake_case             =     ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True)

# compute
_snake_case             =     6_66
_snake_case             =     torch.Generator(device).manual_seed(seed)
_snake_case             =     {'''generator''': generator}
if args.steps is not None:
   _snake_case             =     args.steps

with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa):
   _snake_case             =     pipe(prompt, **generate_kwargs).images[0]

# save image
image.save('''generated.png''')



