



'''simple docstring'''





import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

from transformers import (
    UniSpeechConfig,
    UniSpeechForCTC,
    UniSpeechForPreTraining,
    WavaVecaFeatureExtractor,
    WavaVecaPhonemeCTCTokenizer,
    WavaVecaProcessor,
    logging,
)


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

lowercase_	 =						{
    "post_extract_proj": "feature_projection.projection",
    "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
    "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
    "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
    "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
    "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
    "self_attn_layer_norm": "encoder.layers.*.layer_norm",
    "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
    "fc2": "encoder.layers.*.feed_forward.output_dense",
    "final_layer_norm": "encoder.layers.*.final_layer_norm",
    "encoder.layer_norm": "encoder.layer_norm",
    "w2v_model.layer_norm": "feature_projection.layer_norm",
    "quantizer.weight_proj": "quantizer.weight_proj",
    "quantizer.vars": "quantizer.codevectors",
    "project_q": "project_q",
    "final_proj": "project_hid",
    "w2v_encoder.proj": "ctc_proj",
    "mask_emb": "masked_spec_embed",
}
lowercase_	 =						[
    "ctc_proj",
    "quantizer.weight_proj",
    "quantizer.codevectors",
    "project_q",
    "project_hid",
]




def lowerCAmelCase						(__A						,			__A						,			__A						,			__A						,			__A						,			__A):



     """simple docstring"""



     for attribute in key.split('''.'''):
          if is_finetuned:
               if attribute in ["quantizer", "project_q", "project_hid"]:
                    # those layers are only relevant for pretraining and should be dropped
                    return

               if attribute == "ctc_proj":
                    # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models
                    _a											=						"lm_head"

          _a											=						getattr(lowerCamelCase__						,			lowerCamelCase__)

     if weight_type is not None:
          _a											=						getattr(lowerCamelCase__						,			lowerCamelCase__).shape
     else:
          _a											=						hf_pointer.shape

     assert hf_shape == value.shape, (
         F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
         F''' {value.shape} for {full_name}'''
     )

     if weight_type == "weight":
          _a											=						value
     elif weight_type == "weight_g":
          _a											=						value
     elif weight_type == "weight_v":
          _a											=						value
     elif weight_type == "bias":
          _a											=						value
     else:
          _a											=						value

     logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''')




def lowerCAmelCase						(__A						,			__A						,			__A):



     """simple docstring"""



     _a											=						[]
     _a											=						fairseq_model.state_dict()

     _a											=						hf_model.unispeech.feature_extractor

     for name, value in fairseq_dict.items():
          _a											=						False
          if "conv_layers" in name:
               load_conv_layer(
                   lowerCamelCase__						,			lowerCamelCase__						,			lowerCamelCase__						,			lowerCamelCase__						,			hf_model.config.feat_extract_norm == '''group'''						,			)
               _a											=						True
          else:
               for key, mapped_key in MAPPING.items():
                    _a											=						"unispeech." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
                    if key in name or key.split('''w2v_model.''')[-1] == name.split('''.''')[0]:
                         _a											=						True
                         if "*" in mapped_key:
                              _a											=						name.split(lowerCamelCase__)[0].split('''.''')[-2]
                              _a											=						mapped_key.replace('''*'''						,			lowerCamelCase__)
                         if "weight_g" in name:
                              _a											=						"weight_g"
                         elif "weight_v" in name:
                              _a											=						"weight_v"
                         elif "bias" in name:
                              _a											=						"bias"
                         elif "weight" in name:
                              # TODO: don't match quantizer.weight_proj
                              _a											=						"weight"
                         else:
                              _a											=						None
                         set_recursively(lowerCamelCase__						,			lowerCamelCase__						,			lowerCamelCase__						,			lowerCamelCase__						,			lowerCamelCase__						,			lowerCamelCase__)
                    continue
          if not is_used:
               unused_weights.append(lowerCamelCase__)

     logger.warning(F'''Unused weights: {unused_weights}''')




def lowerCAmelCase						(__A						,			__A						,			__A						,			__A						,			__A):



     """simple docstring"""



     _a											=						full_name.split('''conv_layers.''')[-1]
     _a											=						name.split('''.''')
     _a											=						int(items[0])
     _a											=						int(items[1])

     if type_id == 0:
          if "bias" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
                   F'''{full_name} has size {value.shape}, but'''
                   F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
               )
               _a											=						value
               logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''')
          elif "weight" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
                   F'''{full_name} has size {value.shape}, but'''
                   F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
               )
               _a											=						value
               logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''')
     elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
          if "bias" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
                   F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
                   " found."
               )
               _a											=						value
               logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''')
          elif "weight" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
                   F'''{full_name} has size {value.shape}, but'''
                   F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
               )
               _a											=						value
               logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''')
     else:
          unused_weights.append(lowerCamelCase__)




@torch.no_grad()
def lowerCAmelCase						(__A						,			__A						,			__A=None						,			__A=None						,			__A=True):



     """simple docstring"""



     if config_path is not None:
          _a											=						UniSpeechConfig.from_pretrained(lowerCamelCase__)
     else:
          _a											=						UniSpeechConfig()

     if is_finetuned:
          if dict_path:
               _a											=						Dictionary.load_from_json(lowerCamelCase__)

               # important change bos & pad token id since CTC symbol is <pad> and
               # not <s> as in fairseq
               _a											=						target_dict.pad_index
               _a											=						target_dict.bos_index
               _a											=						target_dict.eos_index
               _a											=						len(target_dict.symbols)
               _a											=						os.path.join(lowerCamelCase__						,			'''vocab.json''')
               if not os.path.isdir(lowerCamelCase__):
                    logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(lowerCamelCase__))
                    return
               os.makedirs(lowerCamelCase__						,			exist_ok=lowerCamelCase__)
               _a											=						target_dict.indices

               # fairseq has the <pad> and <s> switched
               _a											=						42
               _a											=						43
               with open(lowerCamelCase__						,			'''w'''						,			encoding='''utf-8''') as vocab_handle:
                    json.dump(lowerCamelCase__						,			lowerCamelCase__)
               _a											=						WavaVecaPhonemeCTCTokenizer(
                   lowerCamelCase__						,			unk_token=target_dict.unk_word						,			pad_token=target_dict.pad_word						,			bos_token=target_dict.bos_word						,			eos_token=target_dict.eos_word						,			word_delimiter_token='''|'''						,			do_lower_case=lowerCamelCase__						,			)
               _a											=						True if config.feat_extract_norm == "layer" else False
               _a											=						WavaVecaFeatureExtractor(
                   feature_size=1						,			sampling_rate=16_000						,			padding_value=0						,			do_normalize=lowerCamelCase__						,			return_attention_mask=lowerCamelCase__						,			)
               _a											=						WavaVecaProcessor(feature_extractor=lowerCamelCase__						,			tokenizer=lowerCamelCase__)
               processor.save_pretrained(lowerCamelCase__)

          _a											=						UniSpeechForCTC(lowerCamelCase__)
     else:
          _a											=						UniSpeechForPreTraining(lowerCamelCase__)

     if is_finetuned:
          _a											=						fairseq.checkpoint_utils.load_model_ensemble_and_task(
              [checkpoint_path]						,			arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''')[:-1]), '''w2v_path''': checkpoint_path})
     else:
          _a											=						fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path])

     _a											=						model[0].eval()

     recursively_load_weights(lowerCamelCase__						,			lowerCamelCase__						,			lowerCamelCase__)

     hf_unispeech.save_pretrained(lowerCamelCase__)


if __name__ == "__main__":
  lowercase_	 =						argparse.ArgumentParser()
  parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
  parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
  parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
  parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
  parser.add_argument(
      "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
  )
  lowercase_	 =						parser.parse_args()
  convert_unispeech_checkpoint(
      args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
  )











'''simple docstring'''





import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
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 __A    (						A     ,     unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase					: Dict    = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'



 def       a__						(self				,     A=0 )					->  str:


      """simple docstring"""



      _a											=						floats_tensor((1, 3, 128, 128)				,     rng=random.Random(A ) )
      _a											=						np.random.RandomState(A )
      _a											=						{
          '''prompt''': '''A painting of a squirrel eating a burger''',
          '''image''': image,
          '''generator''': generator,
          '''num_inference_steps''': 3,
          '''strength''': 0.75,
          '''guidance_scale''': 7.5,
          '''output_type''': '''numpy''',
      }
      return inputs



 def       a__						(self )					->  str:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.69643, 0.58484, 0.50314, 0.58760, 0.55368, 0.59643, 0.51529, 0.41217, 0.49087] )
      assert np.abs(image_slice - expected_slice ).max() < 1E-1



 def       a__						(self )					->  Tuple:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      _a											=						PNDMScheduler.from_config(pipe.scheduler.config				,     skip_prk_steps=A )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1]

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.61737, 0.54642, 0.53183, 0.54465, 0.52742, 0.60525, 0.49969, 0.40655, 0.48154] )

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



 def       a__						(self )					->  int:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      _a											=						LMSDiscreteScheduler.from_config(pipe.scheduler.config )
      pipe.set_progress_bar_config(disable=A )

      # warmup pass to apply optimizations
      _a											=						pipe(**self.get_dummy_inputs() )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1]

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.52761, 0.59977, 0.49033, 0.49619, 0.54282, 0.50311, 0.47600, 0.40918, 0.45203] )

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



 def       a__						(self )					->  Dict:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      _a											=						EulerDiscreteScheduler.from_config(pipe.scheduler.config )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1]

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.52911, 0.60004, 0.49229, 0.49805, 0.54502, 0.50680, 0.47777, 0.41028, 0.45304] )

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



 def       a__						(self )					->  Tuple:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      _a											=						EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1]

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.52911, 0.60004, 0.49229, 0.49805, 0.54502, 0.50680, 0.47777, 0.41028, 0.45304] )

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



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


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      _a											=						DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1]

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.65331, 0.58277, 0.48204, 0.56059, 0.53665, 0.56235, 0.50969, 0.40009, 0.46552] )

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






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



 '''simple docstring'''







 @property
 def       a__						(self )					->  Tuple:


      """simple docstring"""



      return (
          "CUDAExecutionProvider",
          {
              "gpu_mem_limit": "15000000000",  # 15GB
              "arena_extend_strategy": "kSameAsRequested",
          },
      )



 @property
 def       a__						(self )					->  Any:


      """simple docstring"""



      _a											=						ort.SessionOptions()
      _a											=						False
      return options



 def       a__						(self )					->  str:


      """simple docstring"""



      _a											=						load_image(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
          '''/img2img/sketch-mountains-input.jpg''' )
      _a											=						init_image.resize((768, 512) )
      # using the PNDM scheduler by default
      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(
          '''CompVis/stable-diffusion-v1-4'''				,     revision='''onnx'''				,     safety_checker=A				,     feature_extractor=A				,     provider=self.gpu_provider				,     sess_options=self.gpu_options				,     )
      pipe.set_progress_bar_config(disable=A )

      _a											=						'''A fantasy landscape, trending on artstation'''

      _a											=						np.random.RandomState(0 )
      _a											=						pipe(
          prompt=A				,     image=A				,     strength=0.75				,     guidance_scale=7.5				,     num_inference_steps=10				,     generator=A				,     output_type='''np'''				,     )
      _a											=						output.images
      _a											=						images[0, 255:258, 383:386, -1]

      assert images.shape == (1, 512, 768, 3)
      _a											=						np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019] )
      # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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



 def       a__						(self )					->  Optional[int]:


      """simple docstring"""



      _a											=						load_image(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
          '''/img2img/sketch-mountains-input.jpg''' )
      _a											=						init_image.resize((768, 512) )
      _a											=						LMSDiscreteScheduler.from_pretrained(
          '''runwayml/stable-diffusion-v1-5'''				,     subfolder='''scheduler'''				,     revision='''onnx''' )
      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(
          '''runwayml/stable-diffusion-v1-5'''				,     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 )

      _a											=						'''A fantasy landscape, trending on artstation'''

      _a											=						np.random.RandomState(0 )
      _a											=						pipe(
          prompt=A				,     image=A				,     strength=0.75				,     guidance_scale=7.5				,     num_inference_steps=20				,     generator=A				,     output_type='''np'''				,     )
      _a											=						output.images
      _a											=						images[0, 255:258, 383:386, -1]

      assert images.shape == (1, 512, 768, 3)
      _a											=						np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431] )
      # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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



