-
Notifications
You must be signed in to change notification settings - Fork 12
feat(templates): Add greedy algorithm for gate layering #24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
refraction-ray
merged 3 commits into
tensorcircuit:master
from
Stellogic:feature/gate-layering
Aug 1, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| """ | ||
| This example demonstrates how to use the VQE algorithm to find the ground state | ||
| of a 2D Heisenberg model on a square lattice. It showcases the setup of the lattice, | ||
| the Heisenberg Hamiltonian, a suitable ansatz, and the optimization process. | ||
| """ | ||
|
|
||
| import time | ||
| import optax | ||
| import tensorcircuit as tc | ||
| from tensorcircuit.templates.lattice import SquareLattice, get_compatible_layers | ||
| from tensorcircuit.templates.hamiltonians import heisenberg_hamiltonian | ||
|
|
||
| # Use JAX for high-performance, especially on GPU. | ||
| K = tc.set_backend("jax") | ||
| tc.set_dtype("complex64") | ||
| # On Windows, cotengra's multiprocessing can cause issues, use threads instead. | ||
| tc.set_contractor("cotengra-8192-8192", parallel="threads") | ||
|
|
||
|
|
||
| def run_vqe(): | ||
| """Set up and run the VQE optimization for a 2D Heisenberg model.""" | ||
| n, m, nlayers = 4, 4, 2 | ||
| lattice = SquareLattice(size=(n, m), pbc=True, precompute_neighbors=1) | ||
| h = heisenberg_hamiltonian(lattice, j_coupling=[1.0, 1.0, 0.8]) # Jx, Jy, Jz | ||
| nn_bonds = lattice.get_neighbor_pairs(k=1, unique=True) | ||
| gate_layers = get_compatible_layers(nn_bonds) | ||
| n_params = nlayers * len(nn_bonds) * 3 | ||
|
|
||
| def singlet_init(circuit): | ||
| # A good initial state for Heisenberg ground state search | ||
| nq = circuit._nqubits | ||
| for i in range(0, nq - 1, 2): | ||
| j = (i + 1) % nq | ||
| circuit.X(i) | ||
| circuit.H(i) | ||
| circuit.cnot(i, j) | ||
| circuit.X(j) | ||
| return circuit | ||
|
|
||
| def vqe_forward(param): | ||
| """ | ||
| Defines the VQE ansatz and computes the energy expectation. | ||
| The ansatz consists of nlayers of RZZ, RXX, and RYY entangling layers. | ||
| """ | ||
| c = tc.Circuit(n * m) | ||
| c = singlet_init(c) | ||
| param_idx = 0 | ||
|
|
||
| for _ in range(nlayers): | ||
| for layer in gate_layers: | ||
| for j, k in layer: | ||
| c.rzz(int(j), int(k), theta=param[param_idx]) | ||
| param_idx += 1 | ||
| for layer in gate_layers: | ||
| for j, k in layer: | ||
| c.rxx(int(j), int(k), theta=param[param_idx]) | ||
| param_idx += 1 | ||
| for layer in gate_layers: | ||
| for j, k in layer: | ||
| c.ryy(int(j), int(k), theta=param[param_idx]) | ||
| param_idx += 1 | ||
|
|
||
| return tc.templates.measurements.operator_expectation(c, h) | ||
|
|
||
| vgf = K.jit(K.value_and_grad(vqe_forward)) | ||
| param = tc.backend.implicit_randn(stddev=0.02, shape=[n_params]) | ||
| optimizer = optax.adam(learning_rate=3e-3) | ||
| opt_state = optimizer.init(param) | ||
|
|
||
| @K.jit | ||
| def train_step(param, opt_state): | ||
| """A single training step, JIT-compiled for maximum speed.""" | ||
| loss_val, grads = vgf(param) | ||
| updates, opt_state = optimizer.update(grads, opt_state, param) | ||
| param = optax.apply_updates(param, updates) | ||
| return param, opt_state, loss_val | ||
|
|
||
| print("Starting VQE optimization...") | ||
| for i in range(1000): | ||
| time0 = time.time() | ||
| param, opt_state, loss = train_step(param, opt_state) | ||
| time1 = time.time() | ||
| if i % 10 == 0: | ||
| print( | ||
| f"Step {i:4d}: Loss = {loss:.6f} \t (Time per step: {time1 - time0:.4f}s)" | ||
| ) | ||
|
|
||
| print("Optimization finished.") | ||
| print(f"Final Loss: {loss:.6f}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| run_vqe() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.