


import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

# Register SEW's fairseq modules
from sew_asapp import tasks  # noqa: F401

from transformers import (
    SEWConfig,
    SEWForCTC,
    SEWModel,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
    logging,
)


logging.set_verbosity_info()
__UpperCamelCase    :						Any     =							logging.get_logger(__name__)

__UpperCamelCase    :						Any     =							{
    'post_extract_proj': 'feature_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.upsample.0': 'encoder.upsample.projection',
    'encoder.layer_norm': 'encoder.layer_norm',
    'w2v_model.layer_norm': 'layer_norm',
    'w2v_encoder.proj': 'lm_head',
    'mask_emb': 'masked_spec_embed',
}





def   _UpperCAmelCase       (     UpperCAmelCase      :			List[str]						,	UpperCAmelCase      :			Optional[Any]						,	UpperCAmelCase      :			Dict						,	UpperCAmelCase      :			List[Any]						,	UpperCAmelCase      :			Optional[Any]      ):
      """simple docstring"""




      for attribute in key.split("""."""      ):
            __lowerCamelCase     :      Optional[Any]       						=						getattr(UpperCAmelCase						,	UpperCAmelCase      )

      if weight_type is not None:
            __lowerCamelCase     :      Optional[Any]       						=						getattr(UpperCAmelCase						,	UpperCAmelCase      ).shape
      else:
            __lowerCamelCase     :      List[str]       						=						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":
            __lowerCamelCase     :      Union[str, Any]       						=						value
      elif weight_type == "weight_g":
            __lowerCamelCase     :      Any       						=						value
      elif weight_type == "weight_v":
            __lowerCamelCase     :      Dict       						=						value
      elif weight_type == "bias":
            __lowerCamelCase     :      int       						=						value
      else:
            __lowerCamelCase     :      Optional[Any]       						=						value

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





def   _UpperCAmelCase       (     UpperCAmelCase      :			Optional[int]						,	UpperCAmelCase      :			Union[str, Any]						,	UpperCAmelCase      :			List[Any]      ):
      """simple docstring"""




      __lowerCamelCase     :      Optional[Any]       						=						[]
      __lowerCamelCase     :      List[Any]       						=						fairseq_model.state_dict()

      __lowerCamelCase     :      str       						=						hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor

      for name, value in fairseq_dict.items():
            __lowerCamelCase     :      Optional[int]       						=						False
            if "conv_layers" in name:
                  load_conv_layer(
                      UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	hf_model.config.feat_extract_norm == """group"""						,	)
                  __lowerCamelCase     :      Optional[int]       						=						True
            else:
                  for key, mapped_key in MAPPING.items():
                        __lowerCamelCase     :      Tuple       						=						"""sew.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key

                        if key in name or key.split("""w2v_model."""      )[-1] == name.split("""."""      )[0]:
                              __lowerCamelCase     :      Union[str, Any]       						=						True
                              if "*" in mapped_key:
                                    __lowerCamelCase     :      Dict       						=						name.split(UpperCAmelCase      )[0].split("""."""      )[-2]
                                    __lowerCamelCase     :      Any       						=						mapped_key.replace("""*"""						,	UpperCAmelCase      )
                              if "weight_g" in name:
                                    __lowerCamelCase     :      str       						=						"""weight_g"""
                              elif "weight_v" in name:
                                    __lowerCamelCase     :      Union[str, Any]       						=						"""weight_v"""
                              elif "weight" in name:
                                    __lowerCamelCase     :      Any       						=						"""weight"""
                              elif "bias" in name:
                                    __lowerCamelCase     :      Any       						=						"""bias"""
                              else:
                                    __lowerCamelCase     :      Union[str, Any]       						=						None
                              set_recursively(UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase      )
                        continue
            if not is_used:
                  unused_weights.append(UpperCAmelCase      )

      logger.warning(f"""Unused weights: {unused_weights}"""      )





def   _UpperCAmelCase       (     UpperCAmelCase      :			List[Any]						,	UpperCAmelCase      :			List[str]						,	UpperCAmelCase      :			Union[str, Any]						,	UpperCAmelCase      :			Union[str, Any]						,	UpperCAmelCase      :			List[str]      ):
      """simple docstring"""




      __lowerCamelCase     :      int       						=						full_name.split("""conv_layers."""      )[-1]
      __lowerCamelCase     :      Optional[Any]       						=						name.split("""."""      )
      __lowerCamelCase     :      Optional[int]       						=						int(items[0]      )
      __lowerCamelCase     :      Optional[int]       						=						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."""
                  )
                  __lowerCamelCase     :      int       						=						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."""
                  )
                  __lowerCamelCase     :      Optional[int]       						=						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."
                  )
                  __lowerCamelCase     :      Dict       						=						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."""
                  )
                  __lowerCamelCase     :      Any       						=						value
                  logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""      )
      else:
            unused_weights.append(UpperCAmelCase      )





def   _UpperCAmelCase       (     UpperCAmelCase      :			Dict						,	UpperCAmelCase      :			Tuple      ):
      """simple docstring"""




      __lowerCamelCase     :      List[str]       						=						SEWConfig()
      if is_finetuned:
            __lowerCamelCase     :      Dict       						=						model.wav_encoder.wav_model.cfg
      else:
            __lowerCamelCase     :      Any       						=						model.cfg

      __lowerCamelCase     :      List[str]       						=						fs_config.conv_bias
      __lowerCamelCase     :      List[str]       						=						eval(fs_config.conv_feature_layers      )
      __lowerCamelCase     :      Any       						=						[x[0] for x in conv_layers]
      __lowerCamelCase     :      Tuple       						=						[x[1] for x in conv_layers]
      __lowerCamelCase     :      List[str]       						=						[x[2] for x in conv_layers]
      __lowerCamelCase     :      Dict       						=						"""gelu"""
      __lowerCamelCase     :      str       						=						"""layer""" if fs_config.extractor_mode == """layer_norm""" else """group"""
      __lowerCamelCase     :      Any       						=						0.0
      __lowerCamelCase     :      Optional[int]       						=						fs_config.activation_fn.name
      __lowerCamelCase     :      Optional[Any]       						=						fs_config.encoder_embed_dim
      __lowerCamelCase     :      List[str]       						=						0.0_2
      __lowerCamelCase     :      Dict       						=						fs_config.encoder_ffn_embed_dim
      __lowerCamelCase     :      Dict       						=						1e-5
      __lowerCamelCase     :      str       						=						fs_config.encoder_layerdrop
      __lowerCamelCase     :      int       						=						fs_config.encoder_attention_heads
      __lowerCamelCase     :      List[str]       						=						fs_config.conv_pos_groups
      __lowerCamelCase     :      Tuple       						=						fs_config.conv_pos
      __lowerCamelCase     :      Optional[Any]       						=						len(UpperCAmelCase      )
      __lowerCamelCase     :      Optional[Any]       						=						fs_config.encoder_layers
      __lowerCamelCase     :      str       						=						fs_config.squeeze_factor

      # take care of any params that are overridden by the Wav2VecCtc model
      if is_finetuned:
            __lowerCamelCase     :      Any       						=						model.cfg
            __lowerCamelCase     :      Dict       						=						fs_config.final_dropout
            __lowerCamelCase     :      Any       						=						fs_config.layerdrop
      __lowerCamelCase     :      Union[str, Any]       						=						fs_config.activation_dropout
      __lowerCamelCase     :      Tuple       						=						fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
      __lowerCamelCase     :      List[str]       						=						fs_config.attention_dropout
      __lowerCamelCase     :      Union[str, Any]       						=						fs_config.dropout_input
      __lowerCamelCase     :      List[Any]       						=						fs_config.dropout
      __lowerCamelCase     :      List[str]       						=						fs_config.mask_channel_length
      __lowerCamelCase     :      Optional[Any]       						=						fs_config.mask_channel_prob
      __lowerCamelCase     :      Optional[Any]       						=						fs_config.mask_length
      __lowerCamelCase     :      Optional[Any]       						=						fs_config.mask_prob

      __lowerCamelCase     :      str       						=						"""Wav2Vec2FeatureExtractor"""
      __lowerCamelCase     :      List[str]       						=						"""Wav2Vec2CTCTokenizer"""

      return config





@torch.no_grad()
def   _UpperCAmelCase       (     UpperCAmelCase      :			Any						,	UpperCAmelCase      :			Tuple						,	UpperCAmelCase      :			Union[str, Any]=None						,	UpperCAmelCase      :			Any=None						,	UpperCAmelCase      :			List[str]=True      ):
      """simple docstring"""




      if is_finetuned:
            __lowerCamelCase     :      Optional[Any]       						=						fairseq.checkpoint_utils.load_model_ensemble_and_task(
                [checkpoint_path]						,	arg_overrides={"""data""": """/""".join(dict_path.split("""/"""      )[:-1]      )}      )
      else:
            __lowerCamelCase     :      List[str]       						=						fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]      )

      if config_path is not None:
            __lowerCamelCase     :      List[str]       						=						SEWConfig.from_pretrained(UpperCAmelCase      )
      else:
            __lowerCamelCase     :      List[Any]       						=						convert_config(model[0]						,	UpperCAmelCase      )
      __lowerCamelCase     :      Dict       						=						model[0].eval()

      __lowerCamelCase     :      Any       						=						True if config.feat_extract_norm == """layer""" else False
      __lowerCamelCase     :      Any       						=						WavaVecaFeatureExtractor(
          feature_size=1						,	sampling_rate=16_000						,	padding_value=0						,	do_normalize=UpperCAmelCase						,	return_attention_mask=UpperCAmelCase						,	)

      if is_finetuned:
            if dict_path:
                  __lowerCamelCase     :      Union[str, Any]       						=						Dictionary.load(UpperCAmelCase      )

                  # important change bos & pad token id since CTC symbol is <pad> and
                  # not <s> as in fairseq
                  __lowerCamelCase     :      int       						=						target_dict.pad_index
                  __lowerCamelCase     :      Optional[Any]       						=						target_dict.bos_index
                  __lowerCamelCase     :      Union[str, Any]       						=						target_dict.pad_index
                  __lowerCamelCase     :      Union[str, Any]       						=						target_dict.bos_index
                  __lowerCamelCase     :      List[str]       						=						target_dict.eos_index
                  __lowerCamelCase     :      Tuple       						=						len(target_dict.symbols      )
                  __lowerCamelCase     :      Optional[int]       						=						os.path.join(UpperCAmelCase						,	"""vocab.json"""      )
                  if not os.path.isdir(UpperCAmelCase      ):
                        logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(UpperCAmelCase      )      )
                        return
                  os.makedirs(UpperCAmelCase						,	exist_ok=UpperCAmelCase      )
                  with open(UpperCAmelCase						,	"""w"""						,	encoding="""utf-8"""      ) as vocab_handle:
                        json.dump(target_dict.indices						,	UpperCAmelCase      )
                  __lowerCamelCase     :      int       						=						WavaVecaCTCTokenizer(
                      UpperCAmelCase						,	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=UpperCAmelCase						,	)
                  __lowerCamelCase     :      List[str]       						=						WavaVecaProcessor(feature_extractor=UpperCAmelCase						,	tokenizer=UpperCAmelCase      )
                  processor.save_pretrained(UpperCAmelCase      )

            __lowerCamelCase     :      Tuple       						=						SEWForCTC(UpperCAmelCase      )
      else:
            __lowerCamelCase     :      Any       						=						SEWModel(UpperCAmelCase      )
            feature_extractor.save_pretrained(UpperCAmelCase      )

      recursively_load_weights(UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase      )

      hf_model.save_pretrained(UpperCAmelCase      )


if __name__ == "__main__":
    __UpperCamelCase    :						Union[str, Any]     =							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(
        '--is_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not'
    )
    __UpperCamelCase    :						int     =							parser.parse_args()
    convert_sew_checkpoint(
        args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned
    )






import qiskit





def   _UpperCAmelCase       (     UpperCAmelCase      :			int						,	UpperCAmelCase      :			int      ):
      """simple docstring"""




      __lowerCamelCase     :      Dict       						=						qiskit.Aer.get_backend("""aer_simulator"""      )

      __lowerCamelCase     :      Dict       						=						qiskit.QuantumCircuit(4						,	2      )
      # encode inputs in qubits 0 and 1
      if bita == 1:
            qc_ha.x(0      )
      if bita == 1:
            qc_ha.x(1      )
      qc_ha.barrier()

      # use cnots to write XOR of the inputs on qubit2
      qc_ha.cx(0						,	2      )
      qc_ha.cx(1						,	2      )

      # use ccx / toffoli gate to write AND of the inputs on qubit3
      qc_ha.ccx(0						,	1						,	3      )
      qc_ha.barrier()

      # extract outputs
      qc_ha.measure(2						,	0      )  # extract XOR value
      qc_ha.measure(3						,	1      )  # extract AND value

      # Execute the circuit on the qasm simulator
      __lowerCamelCase     :      str       						=						qiskit.execute(UpperCAmelCase						,	UpperCAmelCase						,	shots=1_000      )

      # Return the histogram data of the results of the experiment
      return job.result().get_counts(UpperCAmelCase      )


if __name__ == "__main__":
    __UpperCamelCase    :						List[str]     =							half_adder(1, 1)
    print(F'''Half Adder Output Qubit Counts: {counts}''')



