{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "38b90986-2529-4974-9dbd-931f3089b7fa",
      "metadata": {},
      "source": [
        "---\n",
        "title: \"REST API를 사용한 실행 모드\"\n",
        "description: \"IBM Quantum Compute Service 세션에서 양자 컴퓨팅 작업을 실행하는 방법.\"\n",
        "---\n",
        "\n",
        "<span id=\"execution-modes-using-rest-api\" />\n",
        "\n",
        "# REST API를 사용한 실행 모드\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d501206a-c250-4df7-befc-317678659d32",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "{/*\n",
        "  DO NOT EDIT THIS CELL!!!\n",
        "  This cell's content is generated automatically by a script. Anything you add\n",
        "  here will be removed next time the notebook is run. To add new content, create\n",
        "  a new cell before or after this one.\n",
        "  */}\n",
        "\n",
        "<details>\n",
        "  <summary><b>패키지 버전</b></summary>\n",
        "\n",
        "  이 페이지의 코드는 다음 요구 사항을 바탕으로 개발되었습니다.\n",
        "  이 버전 이상을 사용하시기를 권장합니다.\n",
        "\n",
        "  ```\n",
        "  qiskit[all]~=2.3.0\n",
        "  ```\n",
        "</details>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2153584e-5711-4168-a4a5-0b94d02dd3e7",
      "metadata": {},
      "source": [
        "IBM Quantum 의 기본 워크로드는 필요에 따라 ‘작업(job)’, ‘세션(session)’, ‘배치(batch)’의 세 가지 실행 모드 중 하나를 선택하여 REST API를 통해 실행할 수 있습니다. 이 주제에서는 이러한 모드들에 대해 설명합니다.\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  이 문서는 Python `requests` 모듈을 사용하여 IBM Quantum Compute 서비스의 REST API를 설명합니다. 그러나 이 워크플로는 REST API 처리를 지원하는 모든 언어나 프레임워크를 사용하여 실행할 수 있습니다. 자세한 내용은 [API 참조](/docs/api/qiskit-runtime-rest) 문서를 참조하십시오.\n",
        "</Admonition>\n",
        "\n",
        "<span id=\"job-mode-with-rest-api\" />\n",
        "\n",
        "## REST API를 통한 작업 모드\n",
        "\n",
        "작업 모드에서는 컨텍스트 매니저 없이 Estimator 또는 Sampler에 대한 단일 기본 요청이 수행됩니다. 예시를 보려면 [Estimator](/docs/guides/estimator-rest-api) 와 [Sampler를](/docs/guides/sampler-rest-api) 사용하여 양자 회로를 실행하는 방법을 확인해 보세요.\n",
        "\n",
        "<span id=\"session-mode-with-rest-api\" />\n",
        "\n",
        "## REST API를 통한 세션 모드\n",
        "\n",
        "세션은 양자 컴퓨터에서 다중 작업 반복 워크로드를 효율적으로 실행할 수 있게 해주는 기능입니다. 세션을 사용하면 각 작업을 개별적으로 대기열에 넣는 데서 발생하는 지연을 피할 수 있으며, 이는 고전 리소스와 양자 리소스 간의 빈번한 통신이 필요한 반복적 작업에 특히 유용할 수 있습니다. 세션에 대한 자세한 내용은 [설명서를](/docs/guides/execution-modes) 참조하십시오.\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  오픈 플랜 사용자는 세션 작업을 제출할 수 없습니다.\n",
        "</Admonition>\n",
        "\n",
        "<span id=\"start-a-session\" />\n",
        "\n",
        "### 세션 시작\n",
        "\n",
        "먼저 세션을 만들고 세션 ID를 얻습니다.\n",
        "\n",
        "```python\n",
        "import json\n",
        "import requests\n",
        "\n",
        "sessionsUrl = \"https://quantum.cloud.ibm.com/api/v1/sessions\"\n",
        "auth_id = \"Bearer <YOUR_BEARER_TOKEN>\"\n",
        "backend = \"<BACKEND_NAME>\"\n",
        "crn = \"<SERVICE-CRN>\"\n",
        "\n",
        "headersList = {\n",
        "  \"Accept\": \"application/json\",\n",
        "  \"Content-Type\": \"application/json\",\n",
        "  \"Authorization\": auth_id,\n",
        "  \"Service-CRN\": crn\n",
        "}\n",
        "\n",
        "payload = json.dumps({\n",
        "  \"backend\": backend,\n",
        "  \"mode\": 'dedicated',\n",
        "})\n",
        "\n",
        "response = requests.request(\"POST\", sessionsUrl, data=payload,  headers=headersList)\n",
        "\n",
        "sessionId = response.json()['id']\n",
        "\n",
        "print(response.json())\n",
        "```\n",
        "\n",
        "출력\n",
        "\n",
        "```text\n",
        "{'id': 'crw9s7cdbt40008jxesg'}\n",
        "```\n",
        "\n",
        "<span id=\"close-a-session\" />\n",
        "\n",
        "### 세션 닫기\n",
        "\n",
        "모든 작업이 완료되면 `Session` 을 닫는 것이 좋습니다. 이렇게 하면 후속 사용자의 대기 시간이 줄어듭니다.\n",
        "\n",
        "```python\n",
        "closureURL=\"https://quantum.cloud.ibm.com/api/v1/sessions/\"+sessionId+\"/close\"\n",
        "\n",
        "headersList = {\n",
        "  \"Accept\": \"application/json\",\n",
        "  \"Authorization\": auth_id,\n",
        "  \"Service-CRN\": crn\n",
        "}\n",
        "\n",
        "closure_response = requests.request(\n",
        "    \"DELETE\",\n",
        "    closureURL,\n",
        "    headers=headersList\n",
        "    )\n",
        "\n",
        "print(\"Session closure response ok?:\",closure_response.ok,closure_response.text)\n",
        "```\n",
        "\n",
        "출력\n",
        "\n",
        "```text\n",
        "Session closure response ok?: True\n",
        "```\n",
        "\n",
        "<span id=\"batch-mode-with-rest-api\" />\n",
        "\n",
        "## REST API를 통한 배치 모드\n",
        "\n",
        "또는 요청 페이로드에 `mode` 를 지정하여 배치 작업을 제출할 수 있습니다. 처음부터 모든 작업을 제공할 수 있다면 배치 모드를 사용하면 처리 시간을 단축하는 데 도움이 될 수 있습니다. [실행 모드](/docs/guides/execution-modes#batch-mode) 안내서의 ‘배치 모드’ 섹션에서 자세히 알아보세요.\n",
        "\n",
        "```python\n",
        "import json\n",
        "import requests\n",
        "\n",
        "sessionsUrl = \"https://quantum.cloud.ibm.com/api/v1/sessions\"\n",
        "\n",
        "headersList = {\n",
        "  \"Accept\": \"application/json\",\n",
        "  \"Authorization\": auth_id,\n",
        "  \"Service-CRN\": crn,\n",
        "  'Content-Type': 'application/json'\n",
        "}\n",
        "\n",
        "payload = json.dumps({\n",
        "  \"backend\": backend,\n",
        "  \"instance\": \"hub1/group1/project1\",\n",
        "  \"mode\": \"batch\"\n",
        "})\n",
        "\n",
        "response = requests.request(\"POST\", sessionsUrl, data=payload,  headers=headersList)\n",
        "\n",
        "sessionId = response.json()['id']\n",
        "```\n",
        "\n",
        "<span id=\"examples-of-jobs-submitted-in-a-session\" />\n",
        "\n",
        "## 세션에 제출된 작업의 예시\n",
        "\n",
        "세션이 설정되면 세션 ID를 지정하여 하나 이상의 샘플러 또는 추정기 작업을 동일한 세션에 제출할 수 있습니다.\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  `PUB` 의 `<parameter values>` 은 단일 매개변수이거나 매개변수 목록일 수 있습니다. `numpy` 방송도 지원합니다.\n",
        "</Admonition>\n",
        "\n",
        "<span id=\"estimator-jobs-in-session-mode\" />\n",
        "\n",
        "### 세션 모드에서의 추정기 작업\n",
        "\n",
        "<Tabs>\n",
        "  <TabItem value=\"1 circuit, 4 observables\" label=\"1 circuit, 4 observables\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'estimator',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm, [obs1, obs2, obs3, obs4]]], #primitive unified blocs (PUBs) containing one circuit each.\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"1 circuit, 4 observables, 2 parameter sets\" label=\"1 circuit, 4 observables, 2 parameter sets\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'estimator',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm, [[obs1], [obs2], [obs3], [obs4]], [[vals1], [vals2]]]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"2 circuits, 2 observables\" label=\"2 circuits, 2 observables\">\n",
        "    ```python\n",
        "      job_input = {\n",
        "      'program_id': 'estimator',\n",
        "      \"backend\": backend,\n",
        "      \"session_id\": sessionId, # This specifies the previously created Session\n",
        "      \"params\": {\n",
        "          \"pubs\": [[resulting_qasm, obs1],[resulting_qasm, obs2]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "          \"options\":{\n",
        "                  \"transpilation\":{\"optimization_level\": 1},\n",
        "                  \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                  # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                      },\n",
        "      }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "</Tabs>\n",
        "\n",
        "<span id=\"sampler-jobs-in-session-mode\" />\n",
        "\n",
        "### 샘플러 작업의 세션 모드\n",
        "\n",
        "<Tabs>\n",
        "  <TabItem value=\"1 circuit, no parameters\" label=\"1 circuit, no parameters\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'sampler',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"1 circuit, 3 parameter sets\" label=\"1 circuit, 3 parameter sets\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'sampler',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm, [vals1, vals2, vals3]]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"2 circuits, 1 parameter set\" label=\"2 circuits, 1 parameter set\">\n",
        "    ```python\n",
        "      job_input = {\n",
        "      'program_id': 'sampler',\n",
        "      \"backend\": backend,\n",
        "      \"session_id\": sessionId, # This specifies the previously created Session\n",
        "      \"params\": {\n",
        "          \"pubs\": [[resulting_qasm, [val1]],[resulting_qasm,None,100]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "          \"options\":{\n",
        "                  \"transpilation\":{\"optimization_level\": 1},\n",
        "                  \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                  # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                      },\n",
        "      }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "</Tabs>\n",
        "\n",
        "<span id=\"next-steps\" />\n",
        "\n",
        "## 다음 단계\n",
        "\n",
        "<Admonition type=\"tip\" title=\"권장사항\">\n",
        "  * REST API를 사용한 [샘플러](/docs/guides/sampler-rest-api) 프리미티브의 상세한 예제를 살펴보세요.\n",
        "  * REST API를 활용한 [Estimator](/docs/guides/estimator-rest-api) 기본 요소 예제를 자세히 살펴보세요.\n",
        "  * IBM 퀀텀® 학습의 [비용 함수 강의를](/learning/courses/variational-algorithm-design/cost-functions) 통해 기본 요소를 연습해 보세요.\n",
        "  * [‘트랜스파일’](/docs/guides/transpile) 섹션에서 로컬 환경에서 트랜스파일하는 방법을 알아보세요.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "id": "a1b8767d",
      "source": "© IBM Corp., 2017-2026"
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}