





'''simple docstring'''







import unittest

import numpy as np

from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
   import onnxruntime as ort
class 			_lowercase						(       __a				,		unittest.TestCase					):
     # FIXME: add fast tests
     pass




@nightly
@require_onnxruntime
@require_torch_gpu
class 			_lowercase						(       unittest.TestCase					):







     @property
     def     UpperCamelCase			( self    ) ->	List[Any]:
          return (
              "CUDAExecutionProvider",
              {
                  "gpu_mem_limit": "15000000000",  # 15GB
                  "arena_extend_strategy": "kSameAsRequested",
              },
          )







     @property
     def     UpperCamelCase			( self    ) ->	Optional[int]:
          snake_case				=			ort.SessionOptions()
          snake_case				=			False
          return options







     def     UpperCamelCase			( self    ) ->	List[str]:
          snake_case				=			load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/in_paint/overture-creations-5sI6fQgYIuo.png'''    )
          snake_case				=			load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png'''    )
          snake_case				=			OnnxStableDiffusionInpaintPipeline.from_pretrained(
              '''runwayml/stable-diffusion-inpainting'''    ,   revision='''onnx'''    ,   safety_checker=A__    ,   feature_extractor=A__    ,   provider=self.gpu_provider    ,   sess_options=self.gpu_options    ,   )
          pipe.set_progress_bar_config(disable=A__    )

          snake_case				=			'''A red cat sitting on a park bench'''

          snake_case				=			np.random.RandomState(0    )
          snake_case				=			pipe(
              prompt=A__    ,   image=A__    ,   mask_image=A__    ,   guidance_scale=7.5    ,   num_inference_steps=10    ,   generator=A__    ,   output_type='''np'''    ,   )
          snake_case				=			output.images
          snake_case				=			images[0, 2_55:2_58, 2_55:2_58, -1]

          assert images.shape == (1, 5_12, 5_12, 3)
          snake_case				=			np.array([0.2_5_1_4, 0.3_0_0_7, 0.3_5_1_7, 0.1_7_9_0, 0.2_3_8_2, 0.3_1_6_7, 0.1_9_4_4, 0.2_2_7_3, 0.2_4_6_4]    )

          assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-3







     def     UpperCamelCase			( self    ) ->	int:
          snake_case				=			load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/in_paint/overture-creations-5sI6fQgYIuo.png'''    )
          snake_case				=			load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png'''    )
          snake_case				=			LMSDiscreteScheduler.from_pretrained(
              '''runwayml/stable-diffusion-inpainting'''    ,   subfolder='''scheduler'''    ,   revision='''onnx'''    )
          snake_case				=			OnnxStableDiffusionInpaintPipeline.from_pretrained(
              '''runwayml/stable-diffusion-inpainting'''    ,   revision='''onnx'''    ,   scheduler=A__    ,   safety_checker=A__    ,   feature_extractor=A__    ,   provider=self.gpu_provider    ,   sess_options=self.gpu_options    ,   )
          pipe.set_progress_bar_config(disable=A__    )

          snake_case				=			'''A red cat sitting on a park bench'''

          snake_case				=			np.random.RandomState(0    )
          snake_case				=			pipe(
              prompt=A__    ,   image=A__    ,   mask_image=A__    ,   guidance_scale=7.5    ,   num_inference_steps=20    ,   generator=A__    ,   output_type='''np'''    ,   )
          snake_case				=			output.images
          snake_case				=			images[0, 2_55:2_58, 2_55:2_58, -1]

          assert images.shape == (1, 5_12, 5_12, 3)
          snake_case				=			np.array([0.0_0_8_6, 0.0_0_7_7, 0.0_0_8_3, 0.0_0_9_3, 0.0_1_0_7, 0.0_1_3_9, 0.0_0_9_4, 0.0_0_9_7, 0.0_1_2_5]    )

          assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-3








'''simple docstring'''







import argparse

import torch
from torch import nn

from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration

def    __UpperCamelCase	(	a    : Optional[int]     ) ->Dict:
 snake_case				=			[
     '''encoder.version''',
     '''decoder.version''',
     '''model.encoder.version''',
     '''model.decoder.version''',
     '''decoder.output_projection.weight''',
     '''_float_tensor''',
     '''encoder.embed_positions._float_tensor''',
     '''decoder.embed_positions._float_tensor''',
 ]
 for k in ignore_keys:
  state_dict.pop(a					,   a     )

def    __UpperCamelCase	(	a    : Optional[Any]     ) ->int:
 snake_case				=			list(s_dict.keys()     )
 for key in keys:
  if "transformer_layers" in key:
   snake_case				=			s_dict.pop(a     )
  elif "subsample" in key:
   snake_case				=			s_dict.pop(a     )

def    __UpperCamelCase	(	a    : Optional[int]     ) ->Optional[int]:
 snake_case				,		snake_case				=			emb.weight.shape
 snake_case				=			nn.Linear(a					,   a					,   bias=a     )
 snake_case				=			emb.weight.data
 return lin_layer

def    __UpperCamelCase	(	a    : Any					,   a    : Tuple     ) ->Tuple:
 snake_case				=			torch.load(a					,   map_location='''cpu'''     )
 snake_case				=			mam_aaa['''args''']
 snake_case				=			mam_aaa['''model''']
 snake_case				=			state_dict['''decoder.output_projection.weight''']

 remove_ignore_keys_(a     )
 rename_keys(a     )

 snake_case				=			state_dict['''decoder.embed_tokens.weight'''].shape[0]

 snake_case				=			args.share_decoder_input_output_embed

 snake_case				=			[int(a     ) for i in args.conv_kernel_sizes.split(''','''     )]
 snake_case				=			SpeechaTextConfig(
     vocab_size=a					,   max_source_positions=args.max_source_positions					,   max_target_positions=args.max_target_positions					,   encoder_layers=args.encoder_layers					,   decoder_layers=args.decoder_layers					,   encoder_attention_heads=args.encoder_attention_heads					,   decoder_attention_heads=args.decoder_attention_heads					,   encoder_ffn_dim=args.encoder_ffn_embed_dim					,   decoder_ffn_dim=args.decoder_ffn_embed_dim					,   d_model=args.encoder_embed_dim					,   dropout=args.dropout					,   attention_dropout=args.attention_dropout					,   activation_dropout=args.activation_dropout					,   activation_function='''relu'''					,   num_conv_layers=len(a     )					,   conv_channels=args.conv_channels					,   conv_kernel_sizes=a					,   input_feat_per_channel=args.input_feat_per_channel					,   input_channels=args.input_channels					,   tie_word_embeddings=a					,   num_beams=5					,   max_length=200					,   use_cache=a					,   decoder_start_token_id=2					,   early_stopping=a					,   )

 snake_case				=			SpeechaTextForConditionalGeneration(a     )
 snake_case				,		snake_case				=			model.model.load_state_dict(a					,   strict=a     )
 if len(a     ) > 0 and not set(a     ) <= {
     "encoder.embed_positions.weights",
     "decoder.embed_positions.weights",
 }:
  raise ValueError(
      '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights`  are allowed to be missing,'''
      f""" but all the following weights are missing {missing}"""     )

 if tie_embeds:
  snake_case				=			make_linear_from_emb(model.model.decoder.embed_tokens     )
 else:
  snake_case				=			lm_head_weights

 model.save_pretrained(a     )


if __name__ == "__main__":
   _lowercase       						=			argparse.ArgumentParser()
   # Required parameters
   parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.')
   parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
   _lowercase       						=			parser.parse_args()
   convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)

