QLayer InterfaceΒΆ
SpinQit provides an abstract interface named QLayer to simplify the implementation of variational quantum algorithms and quantum machine learning algorithms. QLayer encapsulates the backend, backend configuration, measurement operation, gradient function, and related components. QLayer can be defined via a decorator named to_qlayer. Developers use this decorator to wrap any function that returns a Circuit. With the to_qlayer decorator, the final result is the measurement result of the quantum circuit produced by the wrapped function and evaluated on the selected backend. QLayer can also work with the optimizers in SpinQit and interfaces for classical machine learning frameworks. These optimizers and frameworks call the gradient function specified in QLayer for gradient-based optimization. The following example shows how to use the to_qlayer decorator.
from spinqit.interface import to_qlayer
from spinqit.algorithm.loss import expval
op = expval(generate_hamiltonian_matrix([('ZI', 1)]))
@to_qlayer(backend_mode='spinq', grad_method='param_shift', measure=op, interface='torch')
def build_circuit(weights_shape, qubit_num):
circ = Circuit()
weight = circ.add_params(shape=weights_shape)
q = circ.allocateQubits(qubit_num)
...
return circ
More configuration information can be provided via to_qlayer:
@to_qlayer(backend_mode='nmr', grad_method='param_shift', measure=expval(hamiltonian), interface='spinq', ip='192.168.8.176', port=55444, account=("user9", "123456"), shots=1024, task_name='nmrgradtest1', task_desc='nmr grad test')
The main parameters include:
-
- backend_mode
- The backend to execute the circuit, and the current options are 'spinq', 'torch', 'cloud', and 'nmr'
- measure
- This parameter must be a function creating a measurement operation. There are four types of measurement operations: states(), probs(mqubits=None), counts(shots=None, mqubits=None) and expval(hamiltonian). Here expval means the expectation value of a Hamiltonian, and the parameter hamiltonian is a scipy.sparse.csr_matrix or a list of (Pauli string, coefficient) pairs.
- interface
- There are four available interfaces: 'torch', 'tf', 'paddle', and 'spinq'. To avoid unnecessary data-type conversions, SpinQit provides interfaces that work with classical machine learning frameworks such as PyTorch, TensorFlow, and PaddlePaddle.
- grad_method
- Each backend supports one or more gradient functions. All the backends support 'param_shift'. In addition, 'torch' supports 'backprop' and 'spinq' supports 'adjoint_differentiation'.
The following table summarizes the gradient methods and measure operations supported by each kind of backend in QLayer.
| Backend Mode | Grad Method | MeasureOp |
| spinq | param_shift | expval |
| adjoint_differentiation | expval | |
| torch | param_shift | expval |
| backprop | expval, state | |
| cloud | param_shift | expval |
| nmr | param_shift | expval |