
import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin




@skip_mps
class        UpperCAmelCase_			( _A  ,       _A  ,       unittest.TestCase     ):


  '''simple docstring'''







  a__           =		IFImgaImgSuperResolutionPipeline
  a__           =		TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""width""", """height"""}
  a__           =		TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""original_image"""}     )
  a__           =		PipelineTesterMixin.required_optional_params - {"""latents"""}
  def 							_lowercase							( self			: List[Any]    )			->	Optional[int]:







    """simple docstring"""






    return self._get_superresolution_dummy_components()
  def 							_lowercase							( self			: Optional[int]			,							UpperCamelCase__			: str			,							UpperCamelCase__			: Dict=0    )			->	Any:







    """simple docstring"""






    if str(UpperCamelCase__    ).startswith("""mps"""    ):
      __magic_name__				     =       torch.manual_seed(UpperCamelCase__    )
    else:
      __magic_name__				     =       torch.Generator(device=UpperCamelCase__    ).manual_seed(UpperCamelCase__    )

    __magic_name__				     =       floats_tensor((1, 3, 32, 32)			,							rng=random.Random(UpperCamelCase__    )    ).to(UpperCamelCase__    )
    __magic_name__				     =       floats_tensor((1, 3, 16, 16)			,							rng=random.Random(UpperCamelCase__    )    ).to(UpperCamelCase__    )

    __magic_name__				     =       {
        """prompt""": """A painting of a squirrel eating a burger""",
        """image""": image,
        """original_image""": original_image,
        """generator""": generator,
        """num_inference_steps""": 2,
        """output_type""": """numpy""",
    }

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







    """simple docstring"""






    self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3    )
  def 							_lowercase							( self			: Union[str, Any]    )			->	Tuple:







    """simple docstring"""






    self._test_save_load_optional_components()
  @unittest.skipIf(torch_device != """cuda"""			,							reason="""float16 requires CUDA"""    )
  def 							_lowercase							( self			: Tuple    )			->	Union[str, Any]:







    """simple docstring"""






    super().test_save_load_floataa(expected_max_diff=1E-1    )
  def 							_lowercase							( self			: str    )			->	Optional[Any]:







    """simple docstring"""






    self._test_attention_slicing_forward_pass(expected_max_diff=1E-2    )
  def 							_lowercase							( self			: Optional[Any]    )			->	Optional[int]:







    """simple docstring"""






    self._test_save_load_local()





  def 							_lowercase							( self			: str    )			->	Dict:







    """simple docstring"""






    self._test_inference_batch_single_identical(
        expected_max_diff=1E-2			,							)



import argparse
from argparse import Namespace

import torch
from torch import nn

from transformers import XGLMConfig, XGLMForCausalLM

def a__    (       A_					):






  '''simple docstring'''





  __magic_name__				     =       [
      """decoder.version""",
      """decoder.output_projection.weight""",
      """_float_tensor""",
      """decoder.embed_positions._float_tensor""",
  ]
  for k in ignore_keys:
    state_dict.pop(A_,     A_					)

def a__    (       A_					):






  '''simple docstring'''





  __magic_name__     ,    __magic_name__				     =       emb.weight.shape
  __magic_name__				     =       nn.Linear(A_,     A_,     bias=A_					)
  __magic_name__				     =       emb.weight.data
  return lin_layer

def a__    (       A_					):






  '''simple docstring'''





  __magic_name__				     =       torch.load(A_,     map_location="""cpu"""					)
  __magic_name__				     =       Namespace(**checkpoint["""cfg"""]["""model"""]					)
  __magic_name__				     =       checkpoint["""model"""]
  remove_ignore_keys_(A_					)
  __magic_name__				     =       state_dict["""decoder.embed_tokens.weight"""].shape[0]

  __magic_name__				     =       {key.replace("""decoder""",     """model"""					): val for key, val in state_dict.items()}

  __magic_name__				     =       XGLMConfig(
      vocab_size=A_,     max_position_embeddings=args.max_target_positions,     num_layers=args.decoder_layers,     attention_heads=args.decoder_attention_heads,     ffn_dim=args.decoder_ffn_embed_dim,     d_model=args.decoder_embed_dim,     layerdrop=args.decoder_layerdrop,     dropout=args.dropout,     attention_dropout=args.attention_dropout,     activation_dropout=args.activation_dropout,     activation_function="""gelu""",     scale_embedding=not args.no_scale_embedding,     tie_word_embeddings=args.share_decoder_input_output_embed,     )

  __magic_name__				     =       XGLMForCausalLM(A_					)
  __magic_name__				     =       model.load_state_dict(A_,     strict=A_					)
  print(A_					)
  __magic_name__				     =       make_linear_from_emb(model.model.embed_tokens					)

  return model


if __name__ == "__main__":
    __lowerCAmelCase			:     Dict           =   argparse.ArgumentParser()
    # Required parameters
    parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.')
    parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
    __lowerCAmelCase			:     List[str]           =   parser.parse_args()
    __lowerCAmelCase			:     str           =   convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path)
    model.save_pretrained(args.pytorch_dump_folder_path)

