





import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    TextToVideoSDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



@skip_mps
class      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					,							unittest.TestCase					):







	'''simple docstring'''
	lowercase_	=    TextToVideoSDPipeline
	lowercase_	=    TEXT_TO_IMAGE_PARAMS
	lowercase_	=    TEXT_TO_IMAGE_BATCH_PARAMS
	# No `output_type`.
	lowercase_	=    frozenset(
	    [
	        "num_inference_steps",
	        "generator",
	        "latents",
	        "return_dict",
	        "callback",
	        "callback_steps",
	    ]					)

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



			'''simple docstring'''



			torch.manual_seed(0)
			lowerCamelCase__:   Optional[int]    						=UNetaDConditionModel(
			    block_out_channels=(32, 64, 64, 64) ,				layers_per_block=2 ,				sample_size=32 ,				in_channels=4 ,				out_channels=4 ,				down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") ,				up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") ,				cross_attention_dim=32 ,				attention_head_dim=4 ,				)
			lowerCamelCase__:   Union[str, Any]    						=DDIMScheduler(
			    beta_start=0.0_0085 ,				beta_end=0.012 ,				beta_schedule="scaled_linear" ,				clip_sample=UpperCAmelCase_ ,				set_alpha_to_one=UpperCAmelCase_ ,				)
			torch.manual_seed(0)
			lowerCamelCase__:   List[str]    						=AutoencoderKL(
			    block_out_channels=[32, 64] ,				in_channels=3 ,				out_channels=3 ,				down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] ,				up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] ,				latent_channels=4 ,				sample_size=128 ,				)
			torch.manual_seed(0)
			lowerCamelCase__:   Optional[int]    						=CLIPTextConfig(
			    bos_token_id=0 ,				eos_token_id=2 ,				hidden_size=32 ,				intermediate_size=37 ,				layer_norm_eps=1E-0_5 ,				num_attention_heads=4 ,				num_hidden_layers=5 ,				pad_token_id=1 ,				vocab_size=1_000 ,				hidden_act="gelu" ,				projection_dim=512 ,				)
			lowerCamelCase__:   Optional[Any]    						=CLIPTextModel(UpperCAmelCase_)
			lowerCamelCase__:   Dict    						=CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")

			lowerCamelCase__:   Tuple    						={
			    "unet": unet,
			    "scheduler": scheduler,
			    "vae": vae,
			    "text_encoder": text_encoder,
			    "tokenizer": tokenizer,
			}
			return components

	def 							SCREAMING_SNAKE_CASE_      (self       :     str ,				UpperCAmelCase_       :     Dict ,				UpperCAmelCase_       :     List[Any]=0) ->Union[str, Any]:



			'''simple docstring'''



			if str(UpperCAmelCase_).startswith("mps"):
					lowerCamelCase__:   Optional[int]    						=torch.manual_seed(UpperCAmelCase_)
			else:
					lowerCamelCase__:   Any    						=torch.Generator(device=UpperCAmelCase_).manual_seed(UpperCAmelCase_)
			lowerCamelCase__:   List[Any]    						={
			    "prompt": "A painting of a squirrel eating a burger",
			    "generator": generator,
			    "num_inference_steps": 2,
			    "guidance_scale": 6.0,
			    "output_type": "pt",
			}
			return inputs

	def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->Optional[int]:



			'''simple docstring'''



			lowerCamelCase__:   List[str]    						="cpu"  # ensure determinism for the device-dependent torch.Generator
			lowerCamelCase__:   Optional[Any]    						=self.get_dummy_components()
			lowerCamelCase__:   List[Any]    						=TextToVideoSDPipeline(**UpperCAmelCase_)
			lowerCamelCase__:   int    						=sd_pipe.to(UpperCAmelCase_)
			sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_)

			lowerCamelCase__:   Any    						=self.get_dummy_inputs(UpperCAmelCase_)
			lowerCamelCase__:   List[Any]    						="np"
			lowerCamelCase__:   Optional[int]    						=sd_pipe(**UpperCAmelCase_).frames
			lowerCamelCase__:   Dict    						=frames[0][-3:, -3:, -1]

			assert frames[0].shape == (64, 64, 3)
			lowerCamelCase__:   Optional[int]    						=np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0])

			assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2

	def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple) ->str:



			'''simple docstring'''



			self._test_attention_slicing_forward_pass(test_mean_pixel_difference=UpperCAmelCase_ ,				expected_max_diff=3E-3)

	@unittest.skipIf(
	    torch_device != "cuda" or not is_xformers_available() ,				reason="XFormers attention is only available with CUDA and `xformers` installed" ,				)
	def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[Any]) ->List[Any]:



			'''simple docstring'''



			self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=UpperCAmelCase_ ,				expected_max_diff=1E-2)

	@unittest.skip(reason="Batching needs to be properly figured out first for this pipeline.")
	def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->str:



			'''simple docstring'''



			pass

	@unittest.skip(reason="Batching needs to be properly figured out first for this pipeline.")
	def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->Optional[Any]:



			'''simple docstring'''



			pass

	@unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline.")
	def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->Optional[int]:



			'''simple docstring'''



			pass







	def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->Any:



			'''simple docstring'''



			return super().test_progress_bar()



@slow
@skip_mps
class      _SCREAMING_SNAKE_CASE		(			unittest.TestCase					):







	'''simple docstring'''

	def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->int:



			'''simple docstring'''



			lowerCamelCase__:   Dict    						=load_numpy(
			    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy")

			lowerCamelCase__:   Optional[int]    						=TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b")
			lowerCamelCase__:   str    						=DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
			lowerCamelCase__:   Tuple    						=pipe.to("cuda")

			lowerCamelCase__:   List[Any]    						="Spiderman is surfing"
			lowerCamelCase__:   Dict    						=torch.Generator(device="cpu").manual_seed(0)

			lowerCamelCase__:   Optional[int]    						=pipe(UpperCAmelCase_ ,				generator=UpperCAmelCase_ ,				num_inference_steps=25 ,				output_type="pt").frames
			lowerCamelCase__:   str    						=video_frames.cpu().numpy()

			assert np.abs(expected_video - video).mean() < 5E-2







	def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->Optional[int]:



			'''simple docstring'''



			lowerCamelCase__:   Optional[Any]    						=load_numpy(
			    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy")

			lowerCamelCase__:   List[str]    						=TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b")
			lowerCamelCase__:   Any    						=pipe.to("cuda")

			lowerCamelCase__:   Dict    						="Spiderman is surfing"
			lowerCamelCase__:   Dict    						=torch.Generator(device="cpu").manual_seed(0)

			lowerCamelCase__:   Optional[int]    						=pipe(UpperCAmelCase_ ,				generator=UpperCAmelCase_ ,				num_inference_steps=2 ,				output_type="pt").frames
			lowerCamelCase__:   List[Any]    						=video_frames.cpu().numpy()

			assert np.abs(expected_video - video).mean() < 5E-2








import argparse
from pathlib import Path

import fairseq
import torch
from fairseq.models.xmod import XMODModel as FairseqXmodModel
from packaging import version

from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse("0.12.2"):
     raise Exception("requires fairseq >= 0.12.2")
if version.parse(fairseq.__version__) > version.parse("2"):
     raise Exception("requires fairseq < v2")

logging.set_verbosity_info()
__A             =       logging.get_logger(__name__)

__A             =       "Hello, World!"
__A             =       "en_XX"





def   lowerCAmelCase_				( __a			,					__a			,					__a	)  ->	List[Any]:







  """simple docstring"""





  lowerCamelCase__:   Any    						=Path("data_bin"	)
  lowerCamelCase__:   int    						=FairseqXmodModel.from_pretrained(
      model_name_or_path=str(Path(__a	).parent	)			,					checkpoint_file=Path(__a	).name			,					_name="xmod_base"			,					arch="xmod_base"			,					task="multilingual_masked_lm"			,					data_name_or_path=str(__a	)			,					bpe="sentencepiece"			,					sentencepiece_model=str(Path(__a	).parent / "sentencepiece.bpe.model"	)			,					src_dict=str(data_dir / "dict.txt"	)			,					)
  xmod.eval()  # disable dropout
  print(__a	)

  lowerCamelCase__:   Optional[int]    						=xmod.model.encoder.sentence_encoder
  lowerCamelCase__:   Tuple    						=XmodConfig(
      vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings			,					hidden_size=xmod.cfg.model.encoder_embed_dim			,					num_hidden_layers=xmod.cfg.model.encoder_layers			,					num_attention_heads=xmod.cfg.model.encoder_attention_heads			,					intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim			,					max_position_embeddings=514			,					type_vocab_size=1			,					layer_norm_eps=1e-5			,					pre_norm=xmod.cfg.model.encoder_normalize_before			,					adapter_reduction_factor=getattr(xmod.cfg.model			,					"bottleneck"			,					2	)			,					adapter_layer_norm=xmod.cfg.model.adapter_layer_norm			,					adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm			,					ln_before_adapter=xmod.cfg.model.ln_before_adapter			,					languages=xmod.cfg.model.languages			,					)
  if classification_head:
    lowerCamelCase__:   Optional[Any]    						=xmod.model.classification_heads["mnli"].out_proj.weight.shape[0]

  print("Our X-MOD config:"			,					__a	)

  lowerCamelCase__:   Tuple    						=XmodForSequenceClassification(__a	) if classification_head else XmodForMaskedLM(__a	)
  model.eval()

  # Now let's copy all the weights.
  # Embeddings
  lowerCamelCase__:   Any    						=xmod_sent_encoder.embed_tokens.weight
  lowerCamelCase__:   List[Any]    						=xmod_sent_encoder.embed_positions.weight
  lowerCamelCase__:   Any    						=torch.zeros_like(
      model.roberta.embeddings.token_type_embeddings.weight	)  # just zero them out b/c xmod doesn't use them.

  lowerCamelCase__:   List[Any]    						=xmod_sent_encoder.layernorm_embedding.weight
  lowerCamelCase__:   Union[str, Any]    						=xmod_sent_encoder.layernorm_embedding.bias

  for i in range(config.num_hidden_layers	):
    # Encoder: start of layer
    lowerCamelCase__:   List[Any]    						=model.roberta.encoder.layer[i]
    lowerCamelCase__:   Union[str, Any]    						=xmod_sent_encoder.layers[i]

    # self attention
    lowerCamelCase__:   Any    						=layer.attention.self
    if not (
        xmod_layer.self_attn.k_proj.weight.data.shape
        == xmod_layer.self_attn.q_proj.weight.data.shape
        == xmod_layer.self_attn.v_proj.weight.data.shape
        == torch.Size((config.hidden_size, config.hidden_size)	)
    ):
      raise AssertionError("Dimensions of self-attention weights do not match."	)

    lowerCamelCase__:   List[str]    						=xmod_layer.self_attn.q_proj.weight
    lowerCamelCase__:   Any    						=xmod_layer.self_attn.q_proj.bias
    lowerCamelCase__:   Any    						=xmod_layer.self_attn.k_proj.weight
    lowerCamelCase__:   Tuple    						=xmod_layer.self_attn.k_proj.bias
    lowerCamelCase__:   Optional[int]    						=xmod_layer.self_attn.v_proj.weight
    lowerCamelCase__:   List[str]    						=xmod_layer.self_attn.v_proj.bias

    # self-attention output
    lowerCamelCase__:   Optional[int]    						=layer.attention.output
    if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:
      raise AssertionError("Dimensions of self-attention output weights do not match."	)
    lowerCamelCase__:   Dict    						=xmod_layer.self_attn.out_proj.weight
    lowerCamelCase__:   Optional[Any]    						=xmod_layer.self_attn.out_proj.bias
    lowerCamelCase__:   List[Any]    						=xmod_layer.self_attn_layer_norm.weight
    lowerCamelCase__:   Dict    						=xmod_layer.self_attn_layer_norm.bias

    # intermediate
    lowerCamelCase__:   Optional[Any]    						=layer.intermediate
    if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
      raise AssertionError("Dimensions of intermediate weights do not match."	)
    lowerCamelCase__:   int    						=xmod_layer.fca.weight
    lowerCamelCase__:   List[str]    						=xmod_layer.fca.bias

    # output
    lowerCamelCase__:   str    						=layer.output
    if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
      raise AssertionError("Dimensions of feed-forward weights do not match."	)
    lowerCamelCase__:   Optional[Any]    						=xmod_layer.fca.weight
    lowerCamelCase__:   int    						=xmod_layer.fca.bias
    lowerCamelCase__:   List[str]    						=xmod_layer.final_layer_norm.weight
    lowerCamelCase__:   List[Any]    						=xmod_layer.final_layer_norm.bias
    if bert_output.adapter_layer_norm is not None:
      lowerCamelCase__:   Tuple    						=xmod_layer.adapter_layer_norm.weight
      lowerCamelCase__:   List[str]    						=xmod_layer.adapter_layer_norm.bias

    if sorted(bert_output.adapter_modules.keys()	) != sorted(xmod_layer.adapter_modules.keys()	):
      raise AssertionError("Lists of language adapters do not match."	)
    for lang_code, adapter in xmod_layer.adapter_modules.items():
      lowerCamelCase__:   Optional[int]    						=bert_output.adapter_modules[lang_code]
      lowerCamelCase__:   Optional[int]    						=xmod_layer.adapter_modules[lang_code]
      lowerCamelCase__:   Any    						=from_adapter.fca.weight
      lowerCamelCase__:   Tuple    						=from_adapter.fca.bias
      lowerCamelCase__:   Optional[Any]    						=from_adapter.fca.weight
      lowerCamelCase__:   Optional[int]    						=from_adapter.fca.bias

    # end of layer

  if xmod_sent_encoder.layer_norm is not None:
    lowerCamelCase__:   Tuple    						=xmod_sent_encoder.layer_norm.weight
    lowerCamelCase__:   Dict    						=xmod_sent_encoder.layer_norm.bias

  if classification_head:
    lowerCamelCase__:   List[Any]    						=xmod.model.classification_heads["mnli"].dense.weight
    lowerCamelCase__:   int    						=xmod.model.classification_heads["mnli"].dense.bias
    lowerCamelCase__:   List[str]    						=xmod.model.classification_heads["mnli"].out_proj.weight
    lowerCamelCase__:   Dict    						=xmod.model.classification_heads["mnli"].out_proj.bias
  else:
    # LM Head
    lowerCamelCase__:   Tuple    						=xmod.model.encoder.lm_head.dense.weight
    lowerCamelCase__:   int    						=xmod.model.encoder.lm_head.dense.bias
    lowerCamelCase__:   List[Any]    						=xmod.model.encoder.lm_head.layer_norm.weight
    lowerCamelCase__:   str    						=xmod.model.encoder.lm_head.layer_norm.bias
    lowerCamelCase__:   str    						=xmod.model.encoder.lm_head.weight
    lowerCamelCase__:   str    						=xmod.model.encoder.lm_head.bias

  # Let's check that we get the same results.
  lowerCamelCase__:   List[str]    						=xmod.encode(__a	).unsqueeze(0	)  # batch of size 1
  model.roberta.set_default_language(__a	)

  lowerCamelCase__:   List[Any]    						=model(__a	)[0]
  if classification_head:
    lowerCamelCase__:   Union[str, Any]    						=xmod.model.classification_heads["mnli"](xmod.extract_features(__a	)	)
  else:
    lowerCamelCase__:   Dict    						=xmod.model(__a			,					lang_id=[SAMPLE_LANGUAGE]	)[0]
  print(our_output.shape			,					their_output.shape	)
  lowerCamelCase__:   Optional[int]    						=torch.max(torch.abs(our_output - their_output	)	).item()
  print(F"""max_absolute_diff = {max_absolute_diff}"""	)  # ~ 1e-7
  lowerCamelCase__:   Tuple    						=torch.allclose(__a			,					__a			,					atol=1e-3	)
  print("Do both models output the same tensors?"			,					"🔥" if success else "💩"	)
  if not success:
    raise Exception("Something went wRoNg"	)

  Path(__a	).mkdir(parents=__a			,					exist_ok=__a	)
  print(F"""Saving model to {pytorch_dump_folder_path}"""	)
  model.save_pretrained(__a	)


if __name__ == "__main__":
     __A             =       argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         "--xmod_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."
     )
     parser.add_argument(
         "--classification_head", action="store_true", help="Whether to convert a final classification head."
     )
     __A             =       parser.parse_args()
     convert_xmod_checkpoint_to_pytorch(
         args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
     )

