Amazon Braket의 양자 작업 예제 - Amazon Braket

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Amazon Braket의 양자 작업 예제

이 섹션에서는 디바이스 선택부터 결과 보기에 이르기까지 예제 양자 작업을 실행하는 단계를 안내합니다. Amazon Braket의 모범 사례로와 같은 시뮬레이터에서 회로를 실행하는 것이 좋습니다SV1.

디바이스 지정

먼저를 선택하고 양자 작업의 디바이스를 지정합니다. 이 예제에서는 시뮬레이터를 선택하는 방법을 보여줍니다SV1.

# choose the on-demand simulator to run the circuit from braket.aws import AwsDevice device = AwsDevice("arn:aws:braket:::device/quantum-simulator/amazon/sv1")

다음과 같이이 디바이스의 일부 속성을 볼 수 있습니다.

print (device.name) for iter in device.properties.action['braket.ir.jaqcd.program']: print(iter)
SV1 ('version', ['1.0', '1.1']) ('actionType', <DeviceActionType.JAQCD: 'braket.ir.jaqcd.program'>) ('supportedOperations', ['ccnot', 'cnot', 'cphaseshift', 'cphaseshift00', 'cphaseshift01', 'cphaseshift10', 'cswap', 'cy', 'cz', 'h', 'i', 'iswap', 'pswap', 'phaseshift', 'rx', 'ry', 'rz', 's', 'si', 'swap', 't', 'ti', 'unitary', 'v', 'vi', 'x', 'xx', 'xy', 'y', 'yy', 'z', 'zz']) ('supportedResultTypes', [ResultType(name='Sample', observables=['x', 'y', 'z', 'h', 'i', 'hermitian'], minShots=1, maxShots=100000), ResultType(name='Expectation', observables=['x', 'y', 'z', 'h', 'i', 'hermitian'], minShots=0, maxShots=100000), ResultType(name='Variance', observables=['x', 'y', 'z', 'h', 'i', 'hermitian'], minShots=0, maxShots=100000), ResultType(name='Probability', observables=None, minShots=1, maxShots=100000), ResultType(name='Amplitude', observables=None, minShots=0, maxShots=0)])

예제 양자 작업 제출

온디맨드 시뮬레이터에서 실행할 예제 양자 작업을 제출합니다.

# create a circuit with a result type circ = Circuit().rx(0, 1).ry(1, 0.2).cnot(0,2).variance(observable=Observable.Z(), target=0) # add another result type circ.probability(target=[0, 2]) # set up S3 bucket (where results are stored) my_bucket = "amzn-s3-demo-bucket" # the name of the bucket my_prefix = "your-folder-name" # the name of the folder in the bucket s3_location = (my_bucket, my_prefix) # submit the quantum task to run my_task = device.run(circ, s3_location, shots=1000, poll_timeout_seconds = 100, poll_interval_seconds = 10) # the positional argument for the S3 bucket is optional if you want to specify a bucket other than the default # get results of the quantum task result = my_task.result()

device.run() 명령은 CreateQuantumTask API를 통해 양자 작업을 생성합니다. 짧은 초기화 시간이 지나면 양자 태스크는 디바이스에서 양자 태스크를 실행하는 용량이 존재할 때까지 대기됩니다. 이 경우 디바이스는 입니다SV1. 디바이스가 계산을 완료하면 Amazon Braket는 호출에 지정된 Amazon S3 위치에 결과를 기록합니다. 위치 인수는 로컬 시뮬레이터를 제외한 모든 디바이스에 s3_location 필요합니다.

참고

Braket 양자 작업 작업은 크기가 3MB로 제한됩니다.

파라미터화된 작업 제출

Amazon Braket 온디맨드 및 로컬 시뮬레이터와 QPUs 작업 제출 시 무료 파라미터의 값 지정도 지원합니다. 다음 예제와 device.run()같이에 대한 inputs 인수를 사용하여이 작업을 수행할 수 있습니다. 는 문자열 부동 소수점 페어의 사전이어야 inputs 합니다. 여기서 키는 파라미터 이름입니다.

파라미터 컴파일은 특정 QPUs. 파라미터 회로를 지원되는 QPU에 양자 작업으로 제출할 때 Braket은 회로를 한 번 컴파일하고 결과를 캐싱합니다. 동일한 회로에 대한 후속 파라미터 업데이트에는 재컴파일이 없으므로 동일한 회로를 사용하는 작업의 런타임이 빨라집니다. Braket은 최상의 결과를 보장하기 위해 회로를 컴파일할 때 하드웨어 공급자의 업데이트된 보정 데이터를 자동으로 사용합니다.

참고

파라미터 컴파일은 펄스 레벨 프로그램을 제외하고 Rigetti Computing의 모든 슈퍼 액티베이션 게이트 기반 QPUs에서 지원됩니다.

from braket.circuits import Circuit, FreeParameter, Observable # create the free parameters alpha = FreeParameter('alpha') beta = FreeParameter('beta') # create a circuit with a result type circ = Circuit().rx(0, alpha).ry(1, alpha).cnot(0,2).xx(0, 2, beta) circ.variance(observable=Observable.Z(), target=0) # add another result type circ.probability(target=[0, 2]) # submit the quantum task to run my_task = device.run(circ, inputs={'alpha': 0.1, 'beta':0.2})

shots를 지정합니다.

shots 인수는 원하는 측정 수를 나타냅니다shots. 와 같은 시뮬레이터는 두 가지 시뮬레이션 모드를 SV1 지원합니다.

  • shots = 0의 경우 시뮬레이터는 정확한 시뮬레이션을 수행하여 모든 결과 유형에 대한 참 값을 반환합니다. (에서는 사용할 수 없습니다TN1.)

  • 값이 0이 아닌 경우 시뮬레이터shots는 출력 분포에서 샘플을 추출하여 실제 QPU의 shot 노이즈를 에뮬레이션합니다. QPUs QPU 디바이스는 shots > 0만 허용합니다.

양자 작업당 최대 샷 수에 대한 자세한 내용은 Braket Quotas를 참조하세요.

결과에 대한 폴링

my_task.result()를 실행할 때 SDK는 양자 작업 생성 시 정의한 파라미터로 결과에 대한 폴링을 시작합니다.

  • poll_timeout_seconds는 온디맨드 시뮬레이터 및/또는 QPU 디바이스에서 양자 작업을 실행할 때 시간 초과되기 전에 양자 작업을 폴링할 초 수입니다. 기본값은 432,000초로, 5일입니다.

  • 참고: Rigetti 및와 같은 QPU 디바이스의 경우 며칠이 걸리는 IonQ것이 좋습니다. 폴링 제한 시간이 너무 짧으면 폴링 시간 내에 결과가 반환되지 않을 수 있습니다. 예를 들어 QPU를 사용할 수 없는 경우 로컬 제한 시간 오류가 반환됩니다.

  • poll_interval_seconds는 양자 작업이 폴링되는 빈도입니다. 온디맨드 시뮬레이터 및 QPU 디바이스에서 양자 작업이 실행될 때 상태를 가져오기 API 위해 Braket를 호출하는 빈도를 지정합니다. 기본값은 1초입니다.

이 비동기 실행은 항상 사용할 수 있는 것은 아닌 QPU 디바이스와의 상호 작용을 용이하게 합니다. 예를 들어 정기 유지 관리 기간 동안 디바이스를 사용할 수 없습니다.

반환된 결과에는 양자 작업과 연결된 메타데이터 범위가 포함됩니다. 다음 명령을 사용하여 측정 결과를 확인할 수 있습니다.

print('Measurement results:\n',result.measurements) print('Counts for collapsed states:\n',result.measurement_counts) print('Probabilities for collapsed states:\n',result.measurement_probabilities)
Measurement results: [[1 0 1] [0 0 0] [1 0 1] ... [0 0 0] [0 0 0] [0 0 0]] Counts for collapsed states: Counter({'000': 761, '101': 226, '010': 10, '111': 3}) Probabilities for collapsed states: {'101': 0.226, '000': 0.761, '111': 0.003, '010': 0.01}

예제 결과 보기

도 지정했으므로 반환된 결과를 볼 ResultType수 있습니다. 결과 유형은 회로에 추가된 순서대로 표시됩니다.

print('Result types include:\n', result.result_types) print('Variance=',result.values[0]) print('Probability=',result.values[1]) # you can plot the result and do some analysis import matplotlib.pyplot as plt plt.bar(result.measurement_counts.keys(), result.measurement_counts.values()); plt.xlabel('bitstrings'); plt.ylabel('counts');
Result types include: [ResultTypeValue(type={'observable': ['z'], 'targets': [0], 'type': 'variance'}, value=0.7062359999999999), ResultTypeValue(type={'targets': [0, 2], 'type': 'probability'}, value=array([0.771, 0. , 0. , 0.229]))] Variance= 0.7062359999999999 Probability= [0.771 0. 0. 0.229]
여러 비트스트링에 대한 개수를 보여주는 막대 차트로, "000"의 막대가 가장 높을 때 700개 이상의 개수가 포함됩니다.