Skip to content

Commit

Permalink
black formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
mbeach-aws committed Oct 15, 2023
1 parent 33e76f8 commit e052c6a
Show file tree
Hide file tree
Showing 4 changed files with 839 additions and 826 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@
"import pennylane as qml\n",
"from pennylane import numpy as np\n",
"\n",
"\n",
"device = qml.device(\"braket.local.qubit\", wires=1)"
]
},
Expand Down Expand Up @@ -207,8 +206,8 @@
"metadata": {},
"outputs": [],
"source": [
"from braket.jobs import hybrid_job\n",
"from braket.jobs import save_job_result\n",
"from braket.jobs import hybrid_job, save_job_result\n",
"\n",
"\n",
"@hybrid_job(device=\"local:pennylane/lightning.qubit\", dependencies=\"requirements.txt\")\n",
"def qubit_rotation_hybrid_job(num_steps=1, stepsize=0.5):\n",
Expand Down Expand Up @@ -349,8 +348,8 @@
}
],
"source": [
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import pandas as pd\n",
"\n",
"df = pd.DataFrame(job.metrics())\n",
"df.sort_values(by=[\"iteration_number\"], inplace=True)\n",
Expand Down Expand Up @@ -410,22 +409,23 @@
"# device_arn = Devices.Amazon.SV1\n",
"device_arn = Devices.Rigetti.AspenM3\n",
"\n",
"@hybrid_job(device=device_arn, dependencies=\"requirements.txt\") # set priority QPU\n",
"\n",
"@hybrid_job(device=device_arn, dependencies=\"requirements.txt\") # set priority QPU\n",
"def qpu_qubit_rotation_hybrid_job(num_steps=10, stepsize=0.5):\n",
" # AWS devices must be declared within the decorated function.\n",
" device = qml.device(\n",
" \"braket.aws.qubit\",\n",
" device_arn=device_arn.value, # Make sure the device ARN matches the hybrid job device ARN\n",
" wires=2,\n",
" shots=1_000\n",
" shots=1_000,\n",
" )\n",
"\n",
" @qml.qnode(device)\n",
" def circuit(params):\n",
" qml.RX(params[0], wires=0)\n",
" qml.RY(params[1], wires=0)\n",
" return qml.expval(qml.PauliZ(0))\n",
" \n",
"\n",
" opt = qml.GradientDescentOptimizer(stepsize=stepsize)\n",
" params = np.array([0.5, 0.75])\n",
"\n",
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def gradient(self, params: np.ndarray):
result = [self.device.run(c, shots=self.shots).result() for c in circuits]

res = [result[i].values[0] for i in range(len(circuits))]
res = np.array(res).reshape(2, len(params), 2 ** self.n_qubits)
res = np.array(res).reshape(2, len(params), 2**self.n_qubits)

grad = np.zeros(len(params))
for i in range(len(params)):
Expand All @@ -130,7 +130,7 @@ def compute_kernel(px: np.ndarray, py: np.ndarray, sigma_list=[0.1, 1]):
"""
x = np.arange(len(px))
y = np.arange(len(py))
K = sum(np.exp(-np.abs(x[:, None] - y[None, :]) ** 2 / (2 * s ** 2)) for s in sigma_list)
K = sum(np.exp(-np.abs(x[:, None] - y[None, :]) ** 2 / (2 * s**2)) for s in sigma_list)
kernel = px @ K @ py
return kernel

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@
"metadata": {},
"outputs": [],
"source": [
"import networkx as nx\n",
"import pennylane as qml\n",
"from pennylane import numpy as np\n",
"import networkx as nx"
"from pennylane import numpy as np"
]
},
{
Expand Down Expand Up @@ -127,10 +127,10 @@
"source": [
"from pennylane import qaoa\n",
"\n",
"p = 2 # number of QAOA layers\n",
"wires = range(num_nodes) # number of qubits\n",
"p = 2 # number of QAOA layers\n",
"wires = range(num_nodes) # number of qubits\n",
"\n",
"params = np.random.rand(2, p) # random initial parameters\n",
"params = np.random.rand(2, p) # random initial parameters\n",
"\n",
"cost_h, mixer_h = qaoa.maxcut(graph)\n",
"\n",
Expand Down Expand Up @@ -221,8 +221,8 @@
"metadata": {},
"outputs": [],
"source": [
"from braket.jobs.metrics import log_metric\n",
"from braket.jobs import get_results_dir\n",
"from braket.jobs.metrics import log_metric\n",
"\n",
"\n",
"def run_qaoa(p=1, steps=10):\n",
Expand Down Expand Up @@ -371,13 +371,13 @@
"@hybrid_job(device=None, input_data=input_file_path)\n",
"def run_qaoa_hybrid_job(p=1, steps=10):\n",
" params = np.random.rand(2, p)\n",
" \n",
"\n",
" braket_task_tracker = Tracker()\n",
"\n",
" graph = nx.read_adjlist(input_file_path, nodetype=int)\n",
" wires = list(graph.nodes)\n",
" cost_h, mixer_h = qaoa.maxcut(graph)\n",
" \n",
"\n",
" dev = qml.device(\"default.qubit\", wires=len(wires))\n",
"\n",
" @qml.qnode(dev)\n",
Expand All @@ -390,15 +390,18 @@
" for i in range(steps):\n",
" params = optimizer.step(cost_function, params)\n",
" cost = float(cost_function(params))\n",
" \n",
"\n",
" log_metric(metric_name=\"loss\", value=cost, iteration_number=i)\n",
"\n",
" # save checkpoint data\n",
" save_job_checkpoint(checkpoint_data={\n",
" \"iteration\": i,\n",
" \"params\": params.numpy(),\n",
" \"cost\": cost,\n",
" }, data_format = PersistedJobDataFormat.PICKLED_V4)\n",
" save_job_checkpoint(\n",
" checkpoint_data={\n",
" \"iteration\": i,\n",
" \"params\": params.numpy(),\n",
" \"cost\": cost,\n",
" },\n",
" data_format=PersistedJobDataFormat.PICKLED_V4,\n",
" )\n",
"\n",
" # save final results\n",
" np.save(\"optimal_params.npy\", params)\n",
Expand Down Expand Up @@ -585,7 +588,7 @@
"source": [
"# May need to wait a bit before metrics show up\n",
"# If metrics aren't there, try again after 5 seconds\n",
"import time \n",
"import time\n",
"\n",
"time.sleep(10)\n",
"print(job.metrics())"
Expand Down Expand Up @@ -619,12 +622,12 @@
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"# A demonstration of plotting the metrics\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib.ticker import MaxNLocator\n",
"\n",
"\n",
"df = pd.DataFrame(job.metrics()).sort_values(\"iteration_number\")\n",
"\n",
"ax = plt.figure().gca()\n",
Expand Down Expand Up @@ -657,6 +660,7 @@
"source": [
"from braket.jobs import load_job_checkpoint\n",
"\n",
"\n",
"@hybrid_job(device=None, input_data=input_file_path, copy_checkpoints_from_job=previous_job_arn)\n",
"def continued_run_qaoa_hybrid_job(p=1, steps=10):\n",
"\n",
Expand All @@ -666,7 +670,7 @@
" start_iteration = checkpoint[\"iteration\"]\n",
" params = checkpoint[\"params\"]\n",
"\n",
" # code below is similar for both hybrid jobs \n",
" # code below is similar for both hybrid jobs\n",
" braket_task_tracker = Tracker()\n",
"\n",
" graph = nx.read_adjlist(input_file_path, nodetype=int)\n",
Expand All @@ -685,7 +689,7 @@
" for i in range(start_iteration, steps):\n",
" params = optimizer.step(cost_function, params)\n",
" cost = float(cost_function(params))\n",
" \n",
"\n",
" log_metric(metric_name=\"loss\", value=cost, iteration_number=i)\n",
"\n",
" # save final results\n",
Expand Down Expand Up @@ -770,7 +774,7 @@
}
],
"source": [
"time.sleep(10) # wait for new metrics to load\n",
"time.sleep(10) # wait for new metrics to load\n",
"continued_job.metrics()"
]
},
Expand Down Expand Up @@ -823,7 +827,9 @@
}
],
"source": [
"print(f\"Estimated cost to run quantum tasks in this notebook: {job.result()['estimated cost'] + continued_job.result()['estimated cost']} USD\")"
"print(\n",
" f\"Estimated cost to run quantum tasks in this notebook: {job.result()['estimated cost'] + continued_job.result()['estimated cost']} USD\"\n",
")"
]
},
{
Expand Down

0 comments on commit e052c6a

Please sign in to comment.