Skip to content

Commit

Permalink
black
Browse files Browse the repository at this point in the history
  • Loading branch information
rryoung98 committed Oct 22, 2024
1 parent e038f77 commit f6a666e
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 31 deletions.
44 changes: 31 additions & 13 deletions algorithms/quantum_opt_rl/QCO.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,9 @@
"# Adjust the optimization level to see how the number of passes changes\n",
"pass_manager = generate_preset_pass_manager(3, backend)\n",
"\n",
"print(f\"The pass manager for {FakeGuadalupeV2.backend_name} has the following passes: \\n\")\n",
"print(\n",
" f\"The pass manager for {FakeGuadalupeV2.backend_name} has the following passes: \\n\"\n",
")\n",
"\n",
"# Print out the passes in the pass manager\n",
"for i, pass_ in enumerate(pass_manager.passes()):\n",
Expand Down Expand Up @@ -404,7 +406,9 @@
"optimization_levels = [0, 1, 2, 3]\n",
"\n",
"\n",
"def optimize_circuits(circuit: QuantumCircuit, optimization_levels: List[int]) -> List[float]:\n",
"def optimize_circuits(\n",
" circuit: QuantumCircuit, optimization_levels: List[int]\n",
") -> List[float]:\n",
" \"\"\"Optimize the circuit at each optimization level\"\"\"\n",
" # Create an empty list to store the times\n",
" times = []\n",
Expand Down Expand Up @@ -852,7 +856,9 @@
],
"source": [
"# 1q gate optimization\n",
"commutative_cancellation = PassManager([CommutativeCancellation(basis_gates=[\"cx\", \"u\", \"id\"])])\n",
"commutative_cancellation = PassManager(\n",
" [CommutativeCancellation(basis_gates=[\"cx\", \"u\", \"id\"])]\n",
")\n",
"\n",
"# Get the result circuit\n",
"result = commutative_cancellation.run(circuit)\n",
Expand Down Expand Up @@ -1360,11 +1366,11 @@
"metadata": {},
"outputs": [],
"source": [
"sub_batch_size = (\n",
" 64 # cardinality of the sub-samples gathered from the current data in the inner loop\n",
")\n",
"sub_batch_size = 64 # cardinality of the sub-samples gathered from the current data in the inner loop\n",
"num_epochs = 10 # optimization steps per batch of data collected\n",
"clip_epsilon = 0.2 # clip value for PPO loss: see the equation in the intro for more context.\n",
"clip_epsilon = (\n",
" 0.2 # clip value for PPO loss: see the equation in the intro for more context.\n",
")\n",
"gamma = 0.99\n",
"lmbda = 0.95\n",
"entropy_eps = 1e-4"
Expand Down Expand Up @@ -1617,7 +1623,9 @@
],
"source": [
"actor_net = agent.model\n",
"policy_module = TensorDictModule(actor_net, in_keys=[\"observation\"], out_keys=[\"loc\", \"scale\"])\n",
"policy_module = TensorDictModule(\n",
" actor_net, in_keys=[\"observation\"], out_keys=[\"loc\", \"scale\"]\n",
")\n",
"print(env.action_spec.shape[-1])\n",
"\n",
"policy_module = ProbabilisticActor(\n",
Expand Down Expand Up @@ -1759,7 +1767,9 @@
}
],
"source": [
"advantage_module = GAE(gamma=gamma, lmbda=lmbda, value_network=value_module, average_gae=True)\n",
"advantage_module = GAE(\n",
" gamma=gamma, lmbda=lmbda, value_network=value_module, average_gae=True\n",
")\n",
"print(advantage_module.__dict__)\n",
"lr = 3e-4\n",
"\n",
Expand All @@ -1779,7 +1789,9 @@
"# loss_module = loss_module.set_keys\n",
"\n",
"optim = torch.optim.Adam(loss_module.parameters(), lr)\n",
"scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optim, total_frames // frames_per_batch, 0.0)"
"scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\n",
" optim, total_frames // frames_per_batch, 0.0\n",
")"
]
},
{
Expand Down Expand Up @@ -1816,7 +1828,9 @@
" subdata = replay_buffer.sample(sub_batch_size)\n",
" loss_vals = loss_module(subdata.to(device))\n",
" loss_value = (\n",
" loss_vals[\"loss_objective\"] + loss_vals[\"loss_critic\"] + loss_vals[\"loss_entropy\"]\n",
" loss_vals[\"loss_objective\"]\n",
" + loss_vals[\"loss_critic\"]\n",
" + loss_vals[\"loss_entropy\"]\n",
" )\n",
"\n",
" # Optimization: backward, grad clipping and optimization step\n",
Expand All @@ -1829,7 +1843,9 @@
"\n",
" logs[\"reward\"].append(tensordict_data[\"next\", \"reward\"].mean().item())\n",
" pbar.update(tensordict_data.numel() * frame_skip)\n",
" cum_reward_str = f\"average reward={logs['reward'][-1]: 4.4f} (init={logs['reward'][0]: 4.4f})\"\n",
" cum_reward_str = (\n",
" f\"average reward={logs['reward'][-1]: 4.4f} (init={logs['reward'][0]: 4.4f})\"\n",
" )\n",
" logs[\"step_count\"].append(tensordict_data[\"step_count\"].max().item())\n",
" stepcount_str = f\"step count (max): {logs['step_count'][-1]}\"\n",
" logs[\"lr\"].append(optim.param_groups[0][\"lr\"])\n",
Expand All @@ -1845,7 +1861,9 @@
" # execute a rollout with the trained policy\n",
" eval_rollout = env.rollout(1000, policy_module)\n",
" logs[\"eval reward\"].append(eval_rollout[\"next\", \"reward\"].mean().item())\n",
" logs[\"eval reward (sum)\"].append(eval_rollout[\"next\", \"reward\"].sum().item())\n",
" logs[\"eval reward (sum)\"].append(\n",
" eval_rollout[\"next\", \"reward\"].sum().item()\n",
" )\n",
" logs[\"eval step_count\"].append(eval_rollout[\"step_count\"].max().item())\n",
" eval_str = (\n",
" f\"eval cumulative reward: {logs['eval reward (sum)'][-1]: 4.4f} \"\n",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,12 @@ def create_random_circuit(self, seed: Optional[int] = None) -> QuantumCircuit:
"""
if seed is not None:
np.random.seed(seed)
qc_1 = random_circuit(self.num_qubits, np.random.randint(self.min_depth, self.max_depth))
qc_2 = random_circuit(self.num_qubits, np.random.randint(self.min_depth, self.max_depth))
qc_1 = random_circuit(
self.num_qubits, np.random.randint(self.min_depth, self.max_depth)
)
qc_2 = random_circuit(
self.num_qubits, np.random.randint(self.min_depth, self.max_depth)
)

qc_1.compose(qc_2, inplace=True)

Expand All @@ -117,7 +121,9 @@ def _create_tensor_from_circuit(self, circuit: QuantumCircuit) -> torch.Tensor:
"""

# The tensor is of shape (num_qubits, num_gates, num_params)
circuit_tensor = torch.zeros((circuit.num_qubits, len(self.qiskit_gates), self.num_actions))
circuit_tensor = torch.zeros(
(circuit.num_qubits, len(self.qiskit_gates), self.num_actions)
)

for _, op in enumerate(circuit):
name = op.operation.name
Expand All @@ -136,7 +142,9 @@ def _create_tensor_from_circuit(self, circuit: QuantumCircuit) -> torch.Tensor:
def get_qiskit_gates(self, seed: Optional[int] = None):
"""Returns a dictionary of all qiskit gates with random parameters"""
qiskit_gates = {
attr: None for attr in dir(standard_gates) if attr[0] in string.ascii_uppercase
attr: None
for attr in dir(standard_gates)
if attr[0] in string.ascii_uppercase
}

# Add random parameters to gates for circuit generation
Expand All @@ -148,7 +156,9 @@ def get_qiskit_gates(self, seed: Optional[int] = None):
]
params = self._generate_params(varnames, seed=seed)
qiskit_gates[gate] = getattr(standard_gates, gate)(**params)
qiskit_gates = OrderedDict({v.name: v for _, v in qiskit_gates.items() if v is not None})
qiskit_gates = OrderedDict(
{v.name: v for _, v in qiskit_gates.items() if v is not None}
)
# Add iSwap gate
qiskit_gates["iswap"] = iSwapGate()
return qiskit_gates
Expand Down
16 changes: 12 additions & 4 deletions qbraid_lab/fire_opal/get-started.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,9 @@
"metadata": {},
"outputs": [],
"source": [
"supported_devices = fireopal.show_supported_devices(credentials=credentials)[\"supported_devices\"]\n",
"supported_devices = fireopal.show_supported_devices(credentials=credentials)[\n",
" \"supported_devices\"\n",
"]\n",
"for name in supported_devices:\n",
" print(name)"
]
Expand Down Expand Up @@ -499,7 +501,9 @@
],
"source": [
"print(f\"Success probability: {100 * bitstring_results[0]['11111111111']:.2f}%\")\n",
"plot_bv_results(bitstring_results[0], hidden_string=\"11111111111\", title=f\"Fire Opal ($n=11$)\")"
"plot_bv_results(\n",
" bitstring_results[0], hidden_string=\"11111111111\", title=f\"Fire Opal ($n=11$)\"\n",
")"
]
},
{
Expand Down Expand Up @@ -548,11 +552,15 @@
"circuit_qiskit = qiskit.QuantumCircuit.from_qasm_str(circuit_qasm)\n",
"ibm_result = sampler.run(circuit_qiskit).result()\n",
"ibm_probabilities = (\n",
" ibm_result.quasi_dists[0].nearest_probability_distribution().binary_probabilities(num_bits=11)\n",
" ibm_result.quasi_dists[0]\n",
" .nearest_probability_distribution()\n",
" .binary_probabilities(num_bits=11)\n",
")\n",
"\n",
"print(f\"Success probability: {100 * ibm_probabilities['11111111111']:.2f}%\")\n",
"plot_bv_results(ibm_probabilities, hidden_string=\"11111111111\", title=f\"{backend_name} ($n=11$)\")"
"plot_bv_results(\n",
" ibm_probabilities, hidden_string=\"11111111111\", title=f\"{backend_name} ($n=11$)\"\n",
")"
]
},
{
Expand Down
4 changes: 3 additions & 1 deletion qbraid_lab/gpu/cirq_VQE_cuQuantum.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,9 @@
"def energy_func(length, h, jr, jc):\n",
" def energy(measurements):\n",
" # Reshape measurement into array that matches grid shape.\n",
" meas_list_of_lists = [measurements[i * length : (i + 1) * length] for i in range(length)]\n",
" meas_list_of_lists = [\n",
" measurements[i * length : (i + 1) * length] for i in range(length)\n",
" ]\n",
" # Convert true/false to +1/-1.\n",
" pm_meas = 1 - 2 * np.array(meas_list_of_lists).astype(np.int32)\n",
"\n",
Expand Down
4 changes: 3 additions & 1 deletion qbraid_lab/gpu/lightning_gpu_benchmark.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,9 @@
" qml.CNOT(wires=[i, (i + 1) % n_wires])\n",
"\n",
" # Measure all qubits\n",
" observables = [qml.PauliZ(n_wires - 1)] + [qml.Identity(i) for i in range(n_wires - 1)]\n",
" observables = [qml.PauliZ(n_wires - 1)] + [\n",
" qml.Identity(i) for i in range(n_wires - 1)\n",
" ]\n",
" return qml.expval(qml.operation.Tensor(*observables))"
]
},
Expand Down
4 changes: 3 additions & 1 deletion qbraid_lab/quantum_jobs/aws_iqm_quantum_jobs.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@
"\n",
"# The IQM Garnet device\n",
"device = AwsDevice(\"arn:aws:braket:eu-north-1::device/qpu/iqm/Garnet\")\n",
"supported_gates = device.properties.action[\"braket.ir.openqasm.program\"].supportedOperations\n",
"supported_gates = device.properties.action[\n",
" \"braket.ir.openqasm.program\"\n",
"].supportedOperations\n",
"# print the supported gate set\n",
"print(\"Gate set supported by the IQM device:\\n\", supported_gates)"
]
Expand Down
8 changes: 6 additions & 2 deletions qbraid_qir/autoqasm_deutsch_jozsa.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,9 @@
"\n",
"\n",
"@aq.gate\n",
"def constant_oracle(q1: aq.Qubit, q2: aq.Qubit, q3: aq.Qubit, q4: aq.Qubit, q5: aq.Qubit):\n",
"def constant_oracle(\n",
" q1: aq.Qubit, q2: aq.Qubit, q3: aq.Qubit, q4: aq.Qubit, q5: aq.Qubit\n",
"):\n",
" pass\n",
"\n",
"\n",
Expand Down Expand Up @@ -239,7 +241,9 @@
"\n",
"\n",
"@aq.gate\n",
"def balanced_oracle(q0: aq.Qubit, q1: aq.Qubit, q2: aq.Qubit, q3: aq.Qubit, q4: aq.Qubit):\n",
"def balanced_oracle(\n",
" q0: aq.Qubit, q1: aq.Qubit, q2: aq.Qubit, q3: aq.Qubit, q4: aq.Qubit\n",
"):\n",
" ins.cnot(q3, q4)\n",
"\n",
"\n",
Expand Down
16 changes: 12 additions & 4 deletions qbraid_qir/microsoft_resource_estimatation.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,9 @@
" AssertionError: If called before `q` has been properly defined.\n",
" \"\"\"\n",
" # All binary vectors of length `n`.\n",
" all_vectors = [np.array([(m >> i) % 2 for i in range(self.n)]) for m in range(2**self.n)]\n",
" all_vectors = [\n",
" np.array([(m >> i) % 2 for i in range(self.n)]) for m in range(2**self.n)\n",
" ]\n",
"\n",
" def vector_in_L(x):\n",
" for y in all_vectors:\n",
Expand Down Expand Up @@ -234,7 +236,9 @@
" for j in range(i + 1, n): # Adjusted to avoid duplication and ensure i < j\n",
" if A[i][j] == 1 and not used[i] and not used[j]:\n",
" edges_group.append((i, j))\n",
" A[i][j] = A[j][i] = 0 # Ensure the edge is removed from both [i, j] and [j, i]\n",
" A[i][j] = A[j][i] = (\n",
" 0 # Ensure the edge is removed from both [i, j] and [j, i]\n",
" )\n",
" used[i] = used[j] = True\n",
" ans.append(edges_group)\n",
" return ans"
Expand Down Expand Up @@ -276,13 +280,17 @@
" circuit += cirq.CZ(qubits[i], qubits[j])\n",
"\n",
" # S gates encoding the vector b.\n",
" circuit += cirq.Moment([cirq.S.on(qubits[i]) for i in range(problem.n) if problem.b[i] == 1])\n",
" circuit += cirq.Moment(\n",
" [cirq.S.on(qubits[i]) for i in range(problem.n) if problem.b[i] == 1]\n",
" )\n",
"\n",
" # Hadamard gates at the end.\n",
" circuit += cirq.Moment([cirq.H(q) for q in qubits])\n",
"\n",
" # Measurements.\n",
" circuit += cirq.Moment([cirq.measure(qubits[i], key=str(i)) for i in range(problem.n)])\n",
" circuit += cirq.Moment(\n",
" [cirq.measure(qubits[i], key=str(i)) for i in range(problem.n)]\n",
" )\n",
"\n",
" return circuit"
]
Expand Down

0 comments on commit f6a666e

Please sign in to comment.