





import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
      from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm







def       A__							(   SCREAMING_SNAKE_CASE__)       ->   int:
  if is_torch_version("""<""" , """2.0.0""") or not hasattr(snake_case_ , """_dynamo"""):
    return False
  return isinstance(snake_case_ , torch._dynamo.eval_frame.OptimizedModule)







def       A__							(   SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = True)       ->   int:
  __snake_case:						Optional[int]			  =						(torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

  __snake_case:						Union[str, Any]			  =						is_compiled_module(snake_case_)
  if is_compiled:
    __snake_case:						Any			  =						model
    __snake_case:						Union[str, Any]			  =						model._orig_mod

  if is_deepspeed_available():
    options += (DeepSpeedEngine,)

  while isinstance(snake_case_ , snake_case_):
    __snake_case:						Union[str, Any]			  =						model.module

  if not keep_fpaa_wrapper:
    __snake_case:						int			  =						getattr(snake_case_ , """forward""")
    __snake_case:						Any			  =						model.__dict__.pop("""_original_forward""" , snake_case_)
    if original_forward is not None:
      while hasattr(snake_case_ , """__wrapped__"""):
        __snake_case:						Any			  =						forward.__wrapped__
        if forward == original_forward:
          break
      __snake_case:						List[str]			  =						forward
    if getattr(snake_case_ , """_converted_to_transformer_engine""" , snake_case_):
      convert_model(snake_case_ , to_transformer_engine=snake_case_)

  if is_compiled:
    __snake_case:						List[Any]			  =						model
    __snake_case:						Optional[Any]			  =						compiled_model

  return model







def       A__							(   )       ->   Union[str, Any]:
  PartialState().wait_for_everyone()







def       A__							(   SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)       ->   Any:
  if PartialState().distributed_type == DistributedType.TPU:
    xm.save(snake_case_ , snake_case_)
  elif PartialState().local_process_index == 0:
    torch.save(snake_case_ , snake_case_)







@contextmanager
def       A__							(   **SCREAMING_SNAKE_CASE__)       ->   Optional[Any]:
  for key, value in kwargs.items():
    __snake_case:						Optional[Any]			  =						str(snake_case_)

  yield

  for key in kwargs:
    if key.upper() in os.environ:
      del os.environ[key.upper()]







def       A__							(   SCREAMING_SNAKE_CASE__)       ->   Optional[Any]:
  if not hasattr(snake_case_ , """__qualname__""") and not hasattr(snake_case_ , """__name__"""):
    __snake_case:						Optional[Any]			  =						getattr(snake_case_ , """__class__""" , snake_case_)
  if hasattr(snake_case_ , """__qualname__"""):
    return obj.__qualname__
  if hasattr(snake_case_ , """__name__"""):
    return obj.__name__
  return str(snake_case_)







def       A__							(   SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)       ->   Union[str, Any]:
  for key, value in source.items():
    if isinstance(snake_case_ , snake_case_):
      __snake_case:						List[Any]			  =						destination.setdefault(snake_case_ , {})
      merge_dicts(snake_case_ , snake_case_)
    else:
      __snake_case:						Optional[int]			  =						value

  return destination







def       A__							(   SCREAMING_SNAKE_CASE__ = None)       ->   Optional[Any]:
  if port is None:
    __snake_case:						List[str]			  =						2_9500
  with socket.socket(socket.AF_INET , socket.SOCK_STREAM) as s:
    return s.connect_ex(("""localhost""", port)) == 0








import math

import numpy as np
import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute







def       A__							(   SCREAMING_SNAKE_CASE__ = 3)       ->   qiskit.result.counts.Counts:
  if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__):
    raise TypeError("""number of qubits must be a integer.""")
  if number_of_qubits <= 0:
    raise ValueError("""number of qubits must be > 0.""")
  if math.floor(SCREAMING_SNAKE_CASE__) != number_of_qubits:
    raise ValueError("""number of qubits must be exact integer.""")
  if number_of_qubits > 10:
    raise ValueError("""number of qubits too large to simulate(>10).""")

  __snake_case:						int			  =						QuantumRegister(SCREAMING_SNAKE_CASE__ , """qr""")
  __snake_case:						List[str]			  =						ClassicalRegister(SCREAMING_SNAKE_CASE__ , """cr""")

  __snake_case:						Optional[Any]			  =						QuantumCircuit(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)

  __snake_case:						Tuple			  =						number_of_qubits

  for i in range(SCREAMING_SNAKE_CASE__):
    quantum_circuit.h(number_of_qubits - i - 1)
    counter -= 1
    for j in range(SCREAMING_SNAKE_CASE__):
      quantum_circuit.cp(np.pi / 2 ** (counter - j) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)

  for k in range(number_of_qubits // 2):
    quantum_circuit.swap(SCREAMING_SNAKE_CASE__ , number_of_qubits - k - 1)

  # measure all the qubits
  quantum_circuit.measure(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)
  # simulate with 10000 shots
  __snake_case:						Union[str, Any]			  =						Aer.get_backend("""qasm_simulator""")
  __snake_case:						Optional[Any]			  =						execute(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , shots=1_0000)

  return job.result().get_counts(SCREAMING_SNAKE_CASE__)


if __name__ == "__main__":
      print(
          f'Total count for quantum fourier transform state is: \
    {quantum_fourier_transform(3)}'
      )






