Share via


Azure Quantum에 특정 형식 회로를 제출하는 방법

패키지를 사용하여 특정 형식의 azure-quantumPython 회로를 Azure Quantum 서비스에 제출하는 방법을 알아봅니다. 이 문서에서는 다음 형식으로 회로를 제출하는 방법을 보여 줍니다.

자세한 내용은 양자 회로를 참조하세요.

참고

Microsoft Quantum Development Kit(클래식 QDK)는 2024년 6월 30일 이후에 더 이상 지원되지 않습니다. 기존 QDK 개발자인 경우 새로운 Azure Quantum Development Kit(최신 QDK) 로 전환하여 양자 솔루션을 계속 개발하는 것이 좋습니다. 자세한 내용은 Q# 코드를 최신 QDK로 마이그레이션을 참조하세요.

사전 요구 사항

Azure Portal Notebook에서 회로를 실행하려면 다음이 필요합니다.

Visual Studio Code 회로를 개발하고 실행하려면 다음도 필요합니다.

새 Jupyter Notebook 만들기

  1. Azure Portal에 로그인하고 이전 단계에서 만든 작업 영역을 선택합니다.
  2. 왼쪽 블레이드에서 Notebooks를 선택합니다.
  3. 내 Notebooks를 클릭하고 새로 추가를 클릭합니다.
  4. 커널 형식에서 IPython를 선택합니다.
  5. 파일 이름을 입력하고 파일 만들기를 클릭합니다.

새 Notebook이 열리면 구독 및 작업 영역 정보를 기반으로 첫 번째 셀에 대한 코드가 자동으로 만들어집니다.

from azure.quantum import Workspace
workspace = Workspace ( 
    resource_id = "", # Your resource_id 
    location = ""  # Your workspace location (for example, "westus") 
)

QIR 형식 회로 제출

QIR(양자 중간 표현)은 양자 프로그래밍 언어/프레임워크와 target에드 양자 계산 플랫폼 간의 공통 인터페이스 역할을 하는 중간 표현입니다. 자세한 내용은 양자 중간 표현을 참조하세요.

  1. QIR 회로를 만듭니다. 예를 들어 다음 코드는 간단한 얽힘 회로를 만듭니다.

    QIR_routine = """%Result = type opaque
    %Qubit = type opaque
    
    define void @ENTRYPOINT__main() #0 {
      call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 0 to %Qubit*))
      call void @__quantum__qis__cx__body(%Qubit* inttoptr (i64 0 to %Qubit*), %Qubit* inttoptr (i64 1 to %Qubit*))
      call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 2 to %Qubit*))
      call void @__quantum__qis__cz__body(%Qubit* inttoptr (i64 2 to %Qubit*), %Qubit* inttoptr (i64 0 to %Qubit*))
      call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 2 to %Qubit*))
      call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 3 to %Qubit*))
      call void @__quantum__qis__cz__body(%Qubit* inttoptr (i64 3 to %Qubit*), %Qubit* inttoptr (i64 1 to %Qubit*))
      call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 3 to %Qubit*))
      call void @__quantum__qis__mz__body(%Qubit* inttoptr (i64 2 to %Qubit*), %Result* inttoptr (i64 0 to %Result*)) #1
      call void @__quantum__qis__mz__body(%Qubit* inttoptr (i64 3 to %Qubit*), %Result* inttoptr (i64 1 to %Result*)) #1
      call void @__quantum__rt__tuple_record_output(i64 2, i8* null)
      call void @__quantum__rt__result_record_output(%Result* inttoptr (i64 0 to %Result*), i8* null)
      call void @__quantum__rt__result_record_output(%Result* inttoptr (i64 1 to %Result*), i8* null)
      ret void
    }
    
    declare void @__quantum__qis__ccx__body(%Qubit*, %Qubit*, %Qubit*)
    declare void @__quantum__qis__cx__body(%Qubit*, %Qubit*)
    declare void @__quantum__qis__cy__body(%Qubit*, %Qubit*)
    declare void @__quantum__qis__cz__body(%Qubit*, %Qubit*)
    declare void @__quantum__qis__rx__body(double, %Qubit*)
    declare void @__quantum__qis__rxx__body(double, %Qubit*, %Qubit*)
    declare void @__quantum__qis__ry__body(double, %Qubit*)
    declare void @__quantum__qis__ryy__body(double, %Qubit*, %Qubit*)
    declare void @__quantum__qis__rz__body(double, %Qubit*)
    declare void @__quantum__qis__rzz__body(double, %Qubit*, %Qubit*)
    declare void @__quantum__qis__h__body(%Qubit*)
    declare void @__quantum__qis__s__body(%Qubit*)
    declare void @__quantum__qis__s__adj(%Qubit*)
    declare void @__quantum__qis__t__body(%Qubit*)
    declare void @__quantum__qis__t__adj(%Qubit*)
    declare void @__quantum__qis__x__body(%Qubit*)
    declare void @__quantum__qis__y__body(%Qubit*)
    declare void @__quantum__qis__z__body(%Qubit*)
    declare void @__quantum__qis__swap__body(%Qubit*, %Qubit*)
    declare void @__quantum__qis__mz__body(%Qubit*, %Result* writeonly) #1
    declare void @__quantum__rt__result_record_output(%Result*, i8*)
    declare void @__quantum__rt__array_record_output(i64, i8*)
    declare void @__quantum__rt__tuple_record_output(i64, i8*)
    
    attributes #0 = { "entry_point" "output_labeling_schema" "qir_profiles"="base_profile" "required_num_qubits"="4" "required_num_results"="2" }
    attributes #1 = { "irreversible" }
    
    ; module flags
    
    !llvm.module.flags = !{!0, !1, !2, !3}
    
    !0 = !{i32 1, !"qir_major_version", i32 1}
    !1 = !{i32 7, !"qir_minor_version", i32 0}
    !2 = !{i32 1, !"dynamic_qubit_management", i1 false}
    !3 = !{i32 1, !"dynamic_result_management", i1 false}
    """
    
  2. 도우미 함수를 submit_qir_job 만들어 QIR 회로를 에 제출합니다 target. 입력 및 출력 데이터 형식은 각각 및 microsoft.quantum-results.v1qir.v1 지정됩니다.

    # Submit the job with proper input and output data formats
    def submit_qir_job(target, input, name, count=100):
        job = target.submit(
            input_data=input, 
            input_data_format="qir.v1",
            output_data_format="microsoft.quantum-results.v1",
            name=name,
            input_params = {
                "entryPoint": "ENTRYPOINT__main",
                "arguments": [],
                "count": count
                }
        )
    
        print(f"Queued job: {job.id}")
        job.wait_until_completed()
        print(f"Job completed with state: {job.details.status}")
        #if job.details.status == "Succeeded":
        result = job.get_results()
    
        return result
    
  3. 를 target 선택하고 QIR 회로를 Azure Quantum에 제출합니다. 예를 들어 QIR 회로를 IonQ 시뮬레이터 target에 제출합니다.

    target = workspace.get_targets(name="ionq.simulator") 
    result = submit_qir_job(target, QIR_routine, "QIR routine")
    result
    
    {'Histogram': ['(0, 0)', 0.5, '(1, 1)', 0.5]}
    

공급자별 형식의 회로를 Azure Quantum에 제출

Q# 또는 Qiskit와 같은 QIR 언어 외에도 공급자별 형식의 양자 회로를 Azure Quantum에 제출할 수 있습니다. 각 공급자에는 양자 회로를 나타내는 고유한 형식이 있습니다.

JSON 형식을 사용하여 IonQ에 회로 제출

  1. IonQ API 설명서에 설명된 대로 IonQ targets에서 지원하는 언어에 구애받지 않는 JSON 형식을 사용하여 양자 회로를 만듭니다. 예를 들어 다음 샘플에서는 세 개의 큐비트 간에 중첩을 만듭니다.

    circuit = {
        "qubits": 3,
        "circuit": [
            {
            "gate": "h",
            "target": 0
            },
            {
            "gate": "cnot",
            "control": 0,
            "target": 1
            },
            {
            "gate": "cnot",
            "control": 0,
            "target": 2
            },
        ]
    }
    
  2. 회로를 IonQ target에 제출합니다. 다음 예제에서는 Job 개체를 반환하는 IonQ 시뮬레이터를 사용합니다.

    target = workspace.get_targets(name="ionq.simulator")
    job = target.submit(circuit)
    
  3. 작업이 완료될 때까지 기다린 다음, 결과를 가져옵니다.

    results = job.get_results()
    print(results)
    
    .....
    {'duration': 8240356, 'histogram': {'0': 0.5, '7': 0.5}}
    
  4. 그런 다음, Matplotlib를 사용하여 결과를 시각화할 수 있습니다.

    import pylab as pl
    pl.rcParams["font.size"] = 16
    hist = {format(n, "03b"): 0 for n in range(8)}
    hist.update({format(int(k), "03b"): v for k, v in results["histogram"].items()})
    pl.bar(hist.keys(), hist.values())
    pl.ylabel("Probabilities")
    

    IonQ 작업 출력

  5. QPU에서 작업을 실행하기 전에 실행에 소요되는 비용을 예측할 수 있습니다. QPU에서 작업을 실행하는 비용을 예측하기 위해 estimate_cost 메서드를 사용할 수 있습니다.

    target = workspace.get_targets(name="ionq.qpu")
    cost = target.estimate_cost(circuit, shots=500)
    
    print(f"Estimated cost: {cost.estimated_total}")
    

    그러면 예상 비용이 USD로 출력됩니다.

    참고

    최신 가격 책정 세부 정보는 IonQ 가격 책정을 참조하거나 aka.ms/aq/myworkspaces에서 작업 영역을 찾은 다음, 작업 영역의 "공급자" 탭에서 가격 책정 옵션을 확인합니다.

Pulser SDK를 사용하여 PASQAL에 회로 제출

PASQAL에 회로를 제출하려면 Pulser SDK를 사용하여 펄스 시퀀스를 만들고 PASQAL target에 제출할 수 있습니다.

Pulser SDK 설치

Pulser 는 중립 원자 양자 디바이스에 대한 펄스 시퀀스를 구성, 시뮬레이션 및 실행하기 위한 프레임워크입니다. PASQAL은 양자 실험을 양자 프로세서에 제출하기 위한 통과로 설계되었습니다. 자세한 내용은 Pulser 설명서를 참조하세요.

펄스 시퀀스를 제출하려면 먼저 Pulser SDK 패키지를 설치합니다.

try:
    import pulser
except ImportError:
    !pip -q install pulser
    !pip -q install pulser-core

양자 레지스터 만들기

  1. 먼저 필요한 가져오기를 로드합니다.

    import numpy as np
    import pulser
    from pprint import pprint
    from pulser import Pulse, Sequence, Register
    
  2. PASQAL의 QPU는 격자의 잘 정의된 위치에 갇힌 중립 원자로 만들어집니다. 양자 레지스터를 정의하려면 격자에 큐비트 배열을 만듭니다. 예를 들어 다음 코드는 큐비트의 4x4 정사각형 격자를 만듭니다.

    L = 4
    square = np.array([[i, j] for i in range(L) for j in range(L)], dtype=float)
    square -= np.mean(square, axis=0)
    square *= 5
    
    qubits = dict(enumerate(square))
    reg = Register(qubits)
    reg.draw()
    

    16큐비트가 있는 4x4 정사각형 격자의 그림입니다.

펄스 시퀀스 작성

중립 원자는 레이저 펄스로 제어됩니다. Pulser SDK를 사용하면 양자 레지스터에 적용할 펄스 시퀀스를 만들 수 있습니다.

  1. 먼저 펄스 시퀀스를 설정하고 원자를 제어하는 데 사용할 채널을 선언해야 합니다. 예를 들어 다음 코드는 및 ch1의 두 채널을 선언합니다ch0.

    from pulser.devices import Chadoq2
    
    seq = Sequence(reg, Chadoq2)
    
    seq.declare_channel("ch0", "raman_local")
    print("Available channels after declaring 'ch0':")
    pprint(seq.available_channels)
    
    seq.declare_channel("ch1", "rydberg_local", initial_target=4)
    print("\nAvailable channels after declaring 'ch1':")
    pprint(seq.available_channels)
    

    다음가 같은 몇 가지 사항을 고려해야 합니다.

    • Sequence Pulser의 은 양자 레지스터에서 실행될 일련의 연산입니다.
    • 이 코드는 디바이스에서 AnalogDevice 실행할 작업 시퀀스를 설정합니다. AnalogDevice 는 Fresnel1과 동등한 양자 컴퓨터를 나타내는 Pulser의 미리 정의된 디바이스입니다.
  2. 펄스 시퀀스를 만듭니다. 이렇게 하려면 선언한 채널에 펄스를 만들고 추가합니다. 예를 들어 다음 코드는 간단한 펄스를 만들어 채널 ch0에 추가한 다음 복잡한 펄스를 만들어 채널 ch1에 추가합니다.

    seq.target(1, "ch0") # Target qubit 1 with channel "ch0"
    simple_pulse = Pulse.ConstantPulse(200, 2, -10, 0)
    seq.add(simple_pulse, "ch0") # Add the pulse to channel "ch0"
    seq.delay(100, "ch1")
    from pulser.waveforms import RampWaveform, BlackmanWaveform
    
    duration = 1000
    # Create a Blackman waveform with a duration of 1000 ns and an area of pi/2 rad
    amp_wf = BlackmanWaveform(duration, np.pi / 2)  
    # Create a ramp waveform with a duration of 1000 ns and a linear sweep from -20 to 20 rad/µs
    detuning_wf = RampWaveform(duration, -20, 20) 
    
    # Create a pulse with the amplitude waveform amp_wf, the detuning waveform detuning_wf, and a phase of 0 rad.
    complex_pulse = Pulse(amp_wf, detuning_wf, phase=0) 
    complex_pulse.draw()
    seq.add(complex_pulse, "ch1") # Add the pulse to channel "ch1"
    

이미지는 단순하고 복잡한 펄스를 보여줍니다.

단순 및 복합 펄스의 플롯입니다.

시퀀스를 JSON 문자열로 변환

펄스 시퀀스를 제출하려면 Pulser 개체를 입력 데이터로 사용할 수 있는 JSON 문자열로 변환해야 합니다.

import json

# Convert the sequence to a JSON string
def prepare_input_data(seq):
    input_data = {}
    input_data["sequence_builder"] = json.loads(seq.to_abstract_repr())
    to_send = json.dumps(input_data)
    #print(json.dumps(input_data, indent=4, sort_keys=True))
    return to_send

PASQAL에 펄스 시퀀스 제출 target

  1. 먼저 적절한 입력 및 출력 데이터 형식을 설정해야 합니다. 예를 들어 다음 코드는 입력 데이터 형식을 로 pasqal.pulser.v1 설정하고 출력 데이터 형식을 로 pasqal.pulser-results.v1설정합니다.

    # Submit the job with proper input and output data formats
    def submit_job(target, seq):
        job = target.submit(
            input_data=prepare_input_data(seq), # Take the JSON string previously defined as input data
            input_data_format="pasqal.pulser.v1", 
            output_data_format="pasqal.pulser-results.v1",
            name="PASQAL sequence",
            shots=100 # Number of shots
        )
    
        print(f"Queued job: {job.id}")
        job.wait_until_completed()
        print(f"Job completed with state: {job.details.status}")
        result = job.get_results()
    
        return result
    

    참고

    QPU에서 회로를 실행하는 데 필요한 시간은 현재 큐 시간에 따라 다릅니다. 작업 영역의 공급자 블레이드를 target 선택하여 의 평균 큐 시간을 볼 수 있습니다.

  2. 프로그램을 PASQAL에 제출합니다. 예를 들어 프로그램을 PASQAL Emu-TN target에 제출할 수 있습니다.

    target = workspace.get_targets(name="pasqal.sim.emu-tn")
    submit_job(target, seq)
    
    {'0000000000000000': 59,
     '0000100000000000': 39,
     '0100000000000000': 1,
     '0100100000000000': 1}
    

OpenQASM을 사용하여 Quantinuum에 회로 제출

  1. OpenQASM 표현으로 양자 회로를 만듭니다. 예를 들어 다음 예제에서는 순간 이동 회로를 만듭니다.

    circuit = """OPENQASM 2.0;
    include "qelib1.inc";
    qreg q[3];
    creg c0[3];
    h q[0];
    cx q[0], q[1];
    cx q[1], q[2];
    measure q[0] -> c0[0];
    measure q[1] -> c0[1];
    measure q[2] -> c0[2];
    """
    

    필요에 따라 파일에서 회로를 로드할 수 있습니다.

    with open("my_teleport.qasm", "r") as f:
        circuit = f.read()
    
  2. 회로를 Quantinuum target에 제출합니다. 다음 예제에서는 Job 개체를 반환하는 Quantinuum API 유효성 검사기를 사용합니다.

    target = workspace.get_targets(name="quantinuum.sim.h1-1sc")
    job = target.submit(circuit, shots=500)
    
  3. 작업이 완료될 때까지 기다린 다음, 결과를 가져옵니다.

    results = job.get_results()
    print(results)
    
    ........
    {'c0': ['000',
    '000',
    '000',
    '000',
    '000',
    '000',
    '000',
    ...
    ]}
    
  4. 그런 다음, Matplotlib를 사용하여 결과를 시각화할 수 있습니다.

    import pylab as pl
    pl.hist(results["c0"])
    pl.ylabel("Counts")
    pl.xlabel("Bitstring")
    

    Quantinuum 작업 출력

    히스토그램을 보면 난수 생성기가 매번 0을 반환하는 것을 알 수 있습니다. 이는 전혀 무작위적이지 않습니다. 이것은 API 유효성 검사기에서 코드가 Quantinuum 하드웨어에서 성공적으로 실행되도록 보장하지만 모든 양자 측정에 대해 0을 반환하기 때문입니다. 실제 난수 생성기의 경우 양자 하드웨어에서 회로를 실행해야 합니다.

  5. QPU에서 작업을 실행하기 전에 실행에 소요되는 비용을 예측할 수 있습니다. QPU에서 작업을 실행하는 비용을 예측하기 위해 estimate_cost 메서드를 사용할 수 있습니다.

    target = workspace.get_targets(name="quantinuum.qpu.h1-1")
    cost = target.estimate_cost(circuit, shots=500)
    
    print(f"Estimated cost: {cost.estimated_total}")
    

    이렇게 하면 HQC(H-System Quantum Credits)의 예상 비용이 출력됩니다.

    참고

    Quantinuum target에 대해 예상 비용을 실행하려면 먼저 [qiskit] 매개 변수를 사용하여 azure-quantumPython 패키지를 다시 로드해야 합니다. 자세한 내용은 azure-quantum Python 패키지 업데이트를 참조하세요.

    참고

    최신 가격 책정 세부 정보는 Azure Quantum 가격 책정을 참조하거나 작업 영역을 찾아 작업 영역의 "공급자" 탭에서 가격 책정 옵션을 확인합니다. aka.ms/aq/myworkspaces.

Quil을 사용하여 Rigetti에 회로 제출

Quil 작업을 제출하는 가장 쉬운 방법은 pyQuil 라이브러리의 도구와 설명서를 사용할 수 있으므로 pyquil-for-azure-quantum 패키지를 사용하는 것입니다. 이 패키지가 없으면 pyQuil을 사용하여 Quil 프로그램을 생성 할 수 있지만 Azure Quantum에 제출할 수는 없습니다.

Quil 프로그램을 수동으로 구성하고 azure-quantum 패키지를 사용하여 직접 제출할 수도 있습니다.

  1. 먼저 필요한 가져오기를 로드합니다.

    from pyquil.gates import CNOT, MEASURE, H
    from pyquil.quil import Program
    from pyquil.quilbase import Declare
    from pyquil_for_azure_quantum import get_qpu, get_qvm
    
  2. 또는 get_qpu 함수를 get_qvm 사용하여 QVM 또는 QPU에 연결합니다.

    qc = get_qvm()  # For simulation
    # qc = get_qpu("Ankaa-2") for submitting to a QPU
    
  3. Quil 프로그램을 만듭니다. 유효한 Quil 프로그램은 허용되지만 읽기 프로그램의 이름은 ro여야 합니다.

    program = Program(
        Declare("ro", "BIT", 2),
        H(0),
        CNOT(0, 1),
        MEASURE(0, ("ro", 0)),
        MEASURE(1, ("ro", 1)),
    ).wrap_in_numshots_loop(5)
    
    # Optionally pass to_native_gates=False to .compile() to skip the compilation stage
    
    result = qc.run(qc.compile(program))
    data_per_shot = result.readout_data["ro"]
    
  4. 여기서 는 data_per_shotnumpy 배열이므로 메서드를 사용할 numpy 수 있습니다.

    assert data_per_shot.shape == (5, 2)
    ro_data_first_shot = data_per_shot[0]
    assert ro_data_first_shot[0] == 1 or ro_data_first_shot[0] == 0
    
  5. 모든 데이터를 출력합니다.

    print("Data from 'ro' register:")
    for i, shot in enumerate(data_per_shot):
        print(f"Shot {i}: {shot}")
    

중요

단일 작업에서 여러 회로 제출은 현재 지원되지 않습니다. 해결 방법으로, 메서드를 backend.run 호출하여 각 회로를 비동기적으로 제출한 다음, 각 작업의 결과를 가져올 수 있습니다. 다음은 그 예입니다.

jobs = []
for circuit in circuits:
    jobs.append(backend.run(circuit, shots=N))

results = []
for job in jobs:
    results.append(job.result())

다음 단계