


import argparse
import re

import torch
from CLAP import create_model

from transformers import AutoFeatureExtractor, ClapConfig, ClapModel


__UpperCamelCase    :						Union[str, Any]     =							{
    'text_branch': 'text_model',
    'audio_branch': 'audio_model.audio_encoder',
    'attn': 'attention.self',
    'self.proj': 'output.dense',
    'attention.self_mask': 'attn_mask',
    'mlp.fc1': 'intermediate.dense',
    'mlp.fc2': 'output.dense',
    'norm1': 'layernorm_before',
    'norm2': 'layernorm_after',
    'bn0': 'batch_norm',
}

__UpperCamelCase    :						Dict     =							AutoFeatureExtractor.from_pretrained('laion/clap-htsat-unfused', truncation='rand_trunc')





def   _UpperCAmelCase       (     UpperCAmelCase      :			Optional[Any]						,	UpperCAmelCase      :			Optional[Any]=False      ):
      """simple docstring"""




      __lowerCamelCase     :      List[Any]       						=						create_model(
          """HTSAT-tiny"""						,	"""roberta"""						,	UpperCAmelCase						,	precision="""fp32"""						,	device="""cuda:0""" if torch.cuda.is_available() else """cpu"""						,	enable_fusion=UpperCAmelCase						,	fusion_type="""aff_2d""" if enable_fusion else None						,	)
      return model, model_cfg





def   _UpperCAmelCase       (     UpperCAmelCase      :			Optional[Any]      ):
      """simple docstring"""




      __lowerCamelCase     :      Dict       						=						{}

      __lowerCamelCase     :      str       						=						r""".*sequential.(\d+).*"""
      __lowerCamelCase     :      Union[str, Any]       						=						r""".*_projection.(\d+).*"""

      for key, value in state_dict.items():
            # check if any key needs to be modified
            for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
                  if key_to_modify in key:
                        __lowerCamelCase     :      Optional[int]       						=						key.replace(UpperCAmelCase						,	UpperCAmelCase      )

            if re.match(UpperCAmelCase						,	UpperCAmelCase      ):
                  # replace sequential layers with list
                  __lowerCamelCase     :      int       						=						re.match(UpperCAmelCase						,	UpperCAmelCase      ).group(1      )

                  __lowerCamelCase     :      List[str]       						=						key.replace(f"""sequential.{sequential_layer}."""						,	f"""layers.{int(UpperCAmelCase      )//3}.linear."""      )
            elif re.match(UpperCAmelCase						,	UpperCAmelCase      ):
                  __lowerCamelCase     :      int       						=						int(re.match(UpperCAmelCase						,	UpperCAmelCase      ).group(1      )      )

                  # Because in CLAP they use `nn.Sequential`...
                  __lowerCamelCase     :      Optional[Any]       						=						1 if projecton_layer == 0 else 2

                  __lowerCamelCase     :      List[str]       						=						key.replace(f"""_projection.{projecton_layer}."""						,	f"""_projection.linear{transformers_projection_layer}."""      )

            if "audio" and "qkv" in key:
                  # split qkv into query key and value
                  __lowerCamelCase     :      int       						=						value
                  __lowerCamelCase     :      Union[str, Any]       						=						mixed_qkv.size(0      ) // 3

                  __lowerCamelCase     :      Optional[int]       						=						mixed_qkv[:qkv_dim]
                  __lowerCamelCase     :      Optional[Any]       						=						mixed_qkv[qkv_dim : qkv_dim * 2]
                  __lowerCamelCase     :      str       						=						mixed_qkv[qkv_dim * 2 :]

                  __lowerCamelCase     :      List[str]       						=						query_layer
                  __lowerCamelCase     :      int       						=						key_layer
                  __lowerCamelCase     :      Dict       						=						value_layer
            else:
                  __lowerCamelCase     :      List[Any]       						=						value

      return model_state_dict





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




      __lowerCamelCase     :      Tuple       						=						init_clap(UpperCAmelCase						,	enable_fusion=UpperCAmelCase      )

      clap_model.eval()
      __lowerCamelCase     :      Union[str, Any]       						=						clap_model.state_dict()
      __lowerCamelCase     :      int       						=						rename_state_dict(UpperCAmelCase      )

      __lowerCamelCase     :      Optional[Any]       						=						ClapConfig()
      __lowerCamelCase     :      int       						=						enable_fusion
      __lowerCamelCase     :      Optional[int]       						=						ClapModel(UpperCAmelCase      )

      # ignore the spectrogram embedding layer
      model.load_state_dict(UpperCAmelCase						,	strict=UpperCAmelCase      )

      model.save_pretrained(UpperCAmelCase      )
      transformers_config.save_pretrained(UpperCAmelCase      )


if __name__ == "__main__":
    __UpperCamelCase    :						List[str]     =							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('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
    parser.add_argument('--enable_fusion', action='store_true', help='Whether to enable fusion or not')
    __UpperCamelCase    :						Any     =							parser.parse_args()

    convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)






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}''')



